I have a question about .net generics. Consider the following code:
public abstract class Test<TKey>
{
TKey Key { get; set; }
}
public class Wrapper<TValue, TKey>
where TValue : Test<TKey>
{
public TValue Value { get; set; }
}
Now, when using this code, I could do something like this:
Wrapper<Test<int>, int> wrapper = new Wrapper<Test<int>, int>();
The int type parameter has to be provided twice. Is it possible to modify the Wrapper definition, to require TValue to be a generic type, and use this ‘nested’ generic type parameter insted of the TKey type parameter?
I’d say this depends on whether or not you really need to expose your
Valueproperty as a specificTValuewhereTValuederives fromTest<T>. In other words, do you need to expose functionality available only to derived classes, or could you simply expose aTest<T>, with all the functionality of the base class?In the latter case, you could simplify your class definition as:
As for the precise functionality you’re seeking: I don’t believe anything quite like that is available in the current version of C#.
That said, another option in your case might be to actually use your
Wrapperclass itself as a base class: