Activator.CreateInstance<T> Vs new

This overload of the "Activator.CreateInstance" method is used by compilers to implement the instantiation of types specified by type parameters using generics.

Say you have the following method:

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

The compiler will convert the "return new T();" to call "CreateInstance".

In general, there is no use for the CreateInstance 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++).

More Info: http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx


I wouldn't call Activator.CreateInstance() redundant.

If you know the type, yes, you'd just use new. However, in situations requiring dynamic loading of unknown types from plugin frameworks or where the type is parsed from a string (from, say, a settings-file), it's extremely useful.

And to answer the question as to the difference between the two, no, under the hood there is no real difference between calling new T() and Activator.CreateInstance<T>(), as has already been pointed out by Andrew Hare.

EDIT: Never mind, I've confused the generic CreateInstance<T>() with the otherwise more normally used CreateInstance(Type type)


Calling new is better performance-wise CreateInstance probably uses reflection which is slow.
If you know the type during design time - use new, even if the two calls were exactly the same (they're not!) why over-complicate your code?

Use Activator.CreateInstance only when you do not know the type of T in design time and you need run-time resolution of the type.