I’m working on a generic method that will operate on custom collections that derive from CollectionBase. The generic method will do more than shown in my sample code, but this represents the essence of my question.
When I try the following I get a compiler error “Type parameter name is not valid at this point” with the argument T indicated in the CreateInstance() call:
public CollectionBase GetInstance<T>() where T : CollectionBase
{
return Activator.CreateInstance(T) as T;
}
Instead, I have to use typeof(T) and pass it to CreateInstance:
public CollectionBase GetInstance<T>() where T : CollectionBase
{
var targetType = typeof (T);
return Activator.CreateInstance(targetType) as T;
}
Not a big deal, but is there another way to declare my GetInstance method so that I can pass T directly into Activator.CreateInstance() as in the first examaple? And is my use of the generic type “T” in this case accepted practice?
I guess the essence of my question is that I assume T to be an actual type. But the compiler error and need to call typeof(T) seem to indicate it’s instead the name of a type.
Yes,
Activator.CreateInstancehas an overload that accepts a generic type argument: