Skip to content

Activator.CreateInstance remarks outdated #9172

Open
@cremor

Description

@cremor

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."

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pri3Indicates issues/PRs that are low priorityarea-System.Runtimedoc-bugProblem with the content; needs to be fixed

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions