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

c# new() constraint with parameters
cannot create an instance of the variable type 't' because it does not have the new() constraint
c# generic constraints
c# class where t new
c# create instance from type
where t class vs where t new
c# generic inherit from type
generic method with multiple type parameters c#

When you have code like the following:

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

The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor.

I have the following workaround:

public static class ParameterlessConstructor<T>
    where T : new()
{
    public static T Create()
    {
        return _func();
    }

    private static Func<T> CreateFunc()
    {
        return Expression.Lambda<Func<T>>( Expression.New( typeof( T ) ) ).Compile();
    }

    private static Func<T> _func = CreateFunc();
}

// Example:
// Foo foo = ParameterlessConstructor<Foo>.Create();

But it doesn't make sense to me why this workaround should be necessary.

I suspect it's a JITting problem. Currently, the JIT reuses the same generated code for all reference type arguments - so a List<string>'s vtable points to the same machine code as that of List<Stream>. That wouldn't work if each new T() call had to be resolved in the JITted code.

Just a guess, but it makes a certain amount of sense.

One interesting little point: in neither case does the parameterless constructor of a value type get called, if there is one (which is vanishingly rare). See my recent blog post for details. I don't know whether there's any way of forcing it in expression trees.

Why does the c# compiler emit Activator.CreateInstance when , That wouldn't work if each new T() call had to be resolved in the In the face of this ambiguity, C# is forced to use a universal method of type creation. Activator. Because the new() generic constraint was added to C# 2.0 in . 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++). If the type is not known at compile time, you can call a non-generic overload of CreateInstance.

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<T>()
    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.

Can the generic Activator.CreateInstance<T> overload be optimized , Would seem to be worth it since this is an intrinsic met CreateInstance for generic classes with the "new()" type constraint. CreateInstance when calling the paramtereless constructor using dynamic code CreateInstance<T>() gets emitted by the compiler when instantiation occurs on a generic type  Problem with Activator.CreateInstance in C#. C# / C Sharp Forums on Bytes. Need help? Post your question and get tips & solutions from a community of 456,769 IT Pros & Developers.

Why is this workaround necessary?

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

Expression<T> 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.

How to: Define a Generic Method with Reflection Emit, A method is not generic just because it belongs to a generic type and uses the [] tarray) where TOutput : class, ICollection<TInput>, new() { TOutput ret = new When you emit calls to methods of generic types, and the type arguments of C#​. VB. MethodInfo createInst = typeof(Activator).GetMethod("CreateInstance", Type. How to emit compiler warnings and errors in C# .NET February 25, 2015 2 Comments In this post we saw how to use the “if” preprocessor in Visual Studio to “communicate” with the compiler.

Interesting observation :)

Here is a simpler variation on your solution:

static T Create<T>() where T : new()
{
  Expression<Func<T>> e = () => new T();
  return e.Compile()();
}

Obviously naive (and possible slow) :)

Optimization and generics, part 1: the new() constraint (updated , This question already has answers here: Why does the c# compiler emit Activator​.CreateInstance when calling new in with a generic type with a new() constraint  Generics (C# Programming Guide) 07/20/2015; 3 minutes to read +8; In this article. Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

This is a little bit faster, since the expression is only compiled once:

public class Foo<T> where T : new()
{
    static Expression<Func<T>> x = () => new T();
    static Func<T> f = x.Compile();

    public static T build()
    {
        return f();
    }
}

Analyzing the performance, this method is just as fast as the more verbose compiled expression and much, much faster than new T() (160 times faster on my test PC) .

For a tiny bit better performance, the build method call can be eliminated and the functor can be returned instead, which the client could cache and call directly.

public static Func<T> BuildFn { get { return f; } }

Dynamic Types, Why does the c# compiler emit Activator.CreateInstance when calling new in with a generic type with a new() constraint? Also, and probably a fairly minor tweak, I'd also prefer TEnumerator to have a generic constraint of IDisposable, although I guess the compiler could just emit a try/finally which would check to see if TEnumerator was disposable and, if so, call Dispose(). Variance aside I love the idea of current being an out parameter.

[PDF] CLR via C#, Fourth Edition_prePress, In my SteppedPattern type, I have a generic type parameter Now I can just call new SteppedPattern(() => new OffsetBucket()) or Instead, when we write new T​() in C#, the compiler emits a call to Activator.CreateInstance. Remarks The Activator.CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.

new in C# 4.0) and discuss what it means from both a language standpoint as well as a runtime methods and properties of the Excel objects you are actually calling. Although dynamic is a real static type in the C# language, the compiler Instead, you must use generic constraints to do anything close to the intended​  When I first started exploring compiler development, I was frustrated that the available material tended toward the high end. So you want to write a C++ compiler! Just parsing C++ is a monumental effort. Most programmers can find endless entertainment writing a compiler for a simple Basic-style dialect.

assembly; that is, the C# compiler emits a managed module that contains a manifest primary thread calls a method defined inside MSCorEE.dll. static void WriteLine() to create new languages and compilers that produce code targeting the CLR. Sure, the syntax you use for defining the type is different depending on. Set only second argument type in generic method. c#,.net,generics,clr. C# Generics simply does not allow you to specify a subset of the type parameters. It's all or nothing. The way to work around this is to write a fluent interface.

Comments
  • I noticed the same thing... but I don't know why.
  • I am using snippet compiler & the compiler doesn't throw any error. Also, the constructor is called when new T() is called.
  • @shahkalpesh: No-one said there'd be an error. The point is that Activator.CreateInstance is slower than the delegate form.
  • @Jon: Is it at the IL level, the call to Activator.CreateInstance inserted? If so, I did not get it from the question.
  • @shahkalpesh: Yes. Run Reflector or ildasm over code using new T() (with a new T() constraint, not a struct constraint) and you'll see it.
  • I guess the immediate followup question would be "why isn't there an appropriate IL instruction for creating an instance of a generic type with an appropriate constraint?" It's not like they couldn't have built that in from the start :)
  • Agreed it really seems like they implemented an API instead of an IL instruction. The comment on the MSDN doc page for Activator.CreateInstance specifically says that it should be called for this scenario. Odd choice, I'm sure there's a good reason.
  • I suspect the reason is to increase JIT'd code sharing. If you had a direct call to a type's constructor in the JIT'd code, then you couldn't share that JIT'd code with another instantiation for a different type, e.g. 'T Create&lt;T&gt;() where T : new() {return new T();}' would share machine code for Create&lt;string&gt;() and Create&lt;ArrayList&gt;().
  • @JonSkeet Looking back at this five years later, it seems as though this is a growing trend: using static methods to mark places where JIT should take over, as opposed to creating new instructions. A good example would be CER.
  • Just a quick note that this is not true anymore sadly. Regardless of constraint, Roslyn ouputs Activator.CreateInstance.
  • I don't think that will work, because it's specifically "new T()" that his workaround is trying to avoid.
  • @Joel Mueller Actually it does work. Expression tree contains NewExpression here.
  • Yes, it's an Expression of Func<T>, not a Func<T>. The "() => new T()" is not producing IL (thus producing Activator.CreateInstance()), but an expression tree which in turn is compiled at runtime when the T is known. The only problem here is that each time you call this function, you recompile this statement.
  • This is brilliant, didnt know this could work. For the uninformed, the compiled IL will have instructions to Expression.New and not Activator.CreateInstance. Feels like cheating though..quite unintuitive and less obvious for me.