Activator.CreateInstance<T> Vs new
Asked Answered
E

5

39

Is there any difference between following two ways of creating an object.

Student s1 = Activator.CreateInstance<Student>();
Student s1 = new Student();
  • Is there any difference in the way constructor is called or in initializing the memory?
  • Per my understanding, the first method looks completely redundant. If the programmer knows data type during design time, he will use the second method.
Electrocardiogram answered 30/10, 2009 at 10:39 Comment(1)
Related: #6582759, #6070161Ambler
I
18

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

Ignatzia answered 30/10, 2009 at 10:47 Comment(4)
It is very common for a type to be unknown at compile time. It is very useful when separating contract (interface) and implementation.Oliva
It would be very hard to write deserialization code without CreateInstance!Komsomolsk
I would call the last paragraph just all out wrong. It's quite common to have a typename in a config and need to instantiate it. I assume you're specifically referring to the generic overload (used in the question) which would require the concrete type at compile time.Wien
@ChadSchouggins Yes in relation to generics is what I was meaning.Ignatzia
C
10

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)

Corner answered 30/10, 2009 at 10:47 Comment(0)
J
5

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.

Jacquie answered 30/10, 2009 at 10:46 Comment(3)
yes, it uses reflection and thus, new T() should be preferred instead of Activator.CreateInstance<T>() (Source).Fiske
@Shimmy Your link is now broken, I tried to fix it but can't get it to work, would you be able to find it back or find the info elsewhere? (I know it's been 8 years lol)Necrotomy
Here's a new better one.Fiske
O
5

One large difference is that

Student s1 = new Student();

will not compile if there is no default constructor on Student, whereas

Student s1 = Activator.CreateInstance<Student>();

will compile even if Student does not have a default constructor. (It will compile, and let you run the program, but if there is no matching constructor you will get an exception, whereas the constructor call will not even compile if the constructor does not exist.)

Similarly, the CreateInstance call is an implicit use of the class, so, for example, Resharper will not know that you are instantiating it, and might tell you that the class is never instantiated.

As mentioned in other answers, the CreateInstance call also allows for the use of a generic type parameter:

T s1 = Activator.CreateInstance<T>();

though you would probably be better off using a new type constraint, since it would give you compile-time assurance that there actually is a constructor to be called.

The Activator.CreateInstance(Type, ...) overloads are much more useful, however.

Oysterman answered 31/3, 2014 at 23:24 Comment(2)
Are you sure? Which constructor would it call, if there is no default one? What parameters it would pass to that constructor?Methodize
@ZarShardan It would throw an exception. My point was that it will still compile; ie: you'll get a runtime error instead of a compiler error. (compiler errors are preferrable.)Oysterman
P
3

No, Activator.CreateInstance<T> simply calls the default constructor under the covers. The only difference between your examples is an extra method call to CreateInstance<T>.

From Activator.CreateInstance<T>:

Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

Pricecutting answered 30/10, 2009 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.