Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance<T> Vs new

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.
like image 887
Palani Avatar asked Oct 30 '09 10:10

Palani


People also ask

What does activator CreateInstance do?

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.

What is activator CreateInstance in net core?

CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.


2 Answers

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

like image 150
Chris Pietschmann Avatar answered Sep 19 '22 13:09

Chris Pietschmann


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)

like image 30
J. Steen Avatar answered Sep 23 '22 13:09

J. Steen