Why does the c# compiler emit Activator.CreateInstance when calling new in with a generic type with a new() constraint?

后端 未结 5 1488
太阳男子
太阳男子 2020-11-27 06:33

When you have code like the following:

static T GenericConstruct() where T : new()
{
    return new T();
}

The C# compiler insist

5条回答
  •  有刺的猬
    2020-11-27 06:56

    This is likely because it is not clear whether T is a value type or reference type. The creation of these two types in a non-generic scenario produce very different IL. In the face of this ambiguity, C# is forced to use a universal method of type creation. Activator.CreateInstance fits the bill.

    Quick experimentation appears to support this idea. If you type in the following code and examine the IL, it will use initobj instead of CreateInstance because there is no ambiguity on the type.

    static void Create()
        where T : struct
    {
        var x = new T();
        Console.WriteLine(x.ToString());
    }
    

    Switching it to a class and new() constraint though still forces an Activator.CreateInstance.

提交回复
热议问题