There are two confusing flavors of CreateInstance
: one that takes an object of type System.Type
as a parameter, another that takes a type parameter T
.
First one:
object Activator.CreateInstance(type As Type) { }
Second one:
T Activator.CreateInstance<T>() { }
The second one is the one that doesn't work for a class without a public parameterless constructor.
Note that it almost never makes sense to even use the second one; in any case where it would be used, it would be better to have a where T : new()
constraint on your class and simply use T
's constructor.
The MSDN documentation agrees:
In general, there is no use for the
CreateInstance
in application code,
because the type must be known at
compile time. If the type is known at
compile time, normal instantiation
syntax can be used (new
operator in
C#, New
in Visual Basic, gcnew
in
C++).
EDIT: I may have spoken too soon; it appears the first version isn't supposed to work either.