Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default(T) versus Activator.CreateInstance(T)

Tags:

c#

generics

I would like to know if the below statements ever return a different result for reference types, or are they identical?

  1. default(T)
  2. Activator.CreateInstance(T)

If they are identical, could you always use default(T), in this example, if the aim was to output the default value of T?:

if (typeof(T).IsValueType || typeof(T) == typeof(String))
{
     return default(T);
}
else
{
     return Activator.CreateInstance<T>();
}

Best way to test if a generic type is a string? (c#)

ta!

like image 650
Cel Avatar asked Aug 28 '11 17:08

Cel


People also ask

What is activator CreateInstance?

Creates an instance of the specified type using the constructor that best matches the specified parameters. CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo) Creates an instance of the specified type using the constructor that best matches the specified parameters.

What is activator CreateInstance in net core?

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.


2 Answers

For reference types, default(T) will be null, whereas the CreateInstance actually returns a new object of type T (or fails if there is no suitable constructor), so the result will never be identical.

like image 135
Tomas Vana Avatar answered Oct 02 '22 19:10

Tomas Vana


They are entirely different.

  1. default(T), when T is a reference type, will always be null.
  2. Activator.CreateInstance<T>() will create a new instance of that type using the default constructor if present, otherwise, throws MissingMethodException.
like image 28
vcsjones Avatar answered Oct 02 '22 18:10

vcsjones