dotnet / dotnet/dotnet-api-docs
Activator.CreateInstance remarks outdated
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
The remarks section of `Activator.CreateInstance()` currently states this:
> In general, there is no use for the `CreateInstance()` 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:
```cs
public class MyType
{
public required string Name { get; set; }
}
public static class MyFactory
{
public static T CreateWithNewConstraint() where T : new()
{
return new T();
}
public static T CreateWithActivator()
{
return Activator.CreateInstance();
}
}
public static class MySample
{
public static void Sample()
{
// This shows compiler error CS9040
var o1 = MyFactory.CreateWithNewConstraint();
// This works fine
var o2 = MyFactory.CreateWithActivator();
}
}
```
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."
Contributor guide
Assessment
This issue has not been assessed yet.