Consider the following class:
public class DerivedClassPool<TBase> where TBase : class { public TBase Get(Type componentType) { // Not important, but you get the idea return Activator.CreateInstance(componentType) as TBase; } public TDerived SomeMethod<TDerived>() where TDerived : TBase { return Get(typeof(TBase)) as TDerived; } }
Note that I restricted the TBase generic class argument to the class: where TBase : class
I also restricted the TDerived generic method argument to TDerived or something derived from this: where TDerived : TBase .
I get an error in the as TDerived line:
A parameter of type "TDerived" cannot be used with the "as" operator because it does not have a class type restriction or a class restriction
I understand that to prevent the error, I need to add a class constraint, so I would get:
where TDerived : class, TBase
Why should I do this when TBase already limited to a class and TDerived is TBase or derived from it?
generics inheritance c #
George Duckett
source share