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

后端 未结 5 1510
太阳男子
太阳男子 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:52

    Why is this workaround necessary?

    Because the new() generic constraint was added to C# 2.0 in .NET 2.0.

    Expression and friends, meanwhile, were added to .NET 3.5.

    So your workaround is necessary because it wasn't possible in .NET 2.0. Meanwhile, (1) using Activator.CreateInstance() was possible, and (2) IL lacks a way to implement 'new T()', so Activator.CreateInstance() was used to implement that behavior.

提交回复
热议问题