Open
Description
The remarks section of Activator.CreateInstance<T>()
currently states this:
In general, there is no use for the
CreateInstance<T>()
generic method 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++).
This is not correct any more. Consider the following example:
public class MyType
{
public required string Name { get; set; }
}
public static class MyFactory
{
public static T CreateWithNewConstraint<T>() where T : new()
{
return new T();
}
public static T CreateWithActivator<T>()
{
return Activator.CreateInstance<T>();
}
}
public static class MySample
{
public static void Sample()
{
// This shows compiler error CS9040
var o1 = MyFactory.CreateWithNewConstraint<MyType>();
// This works fine
var o2 = MyFactory.CreateWithActivator<MyType>();
}
}
Compiler error CS9040 is currently not documented. It has the following message: "'MyType' cannot satisfy the 'new()' constraint on parameter 'T' in the generic type or or method 'MyFactory.CreateWithNewConstraint()' because 'MyType' has required members."