Cel
Cel

Reputation: 6659

default(T) versus Activator.CreateInstance(T)

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!

Upvotes: 12

Views: 3903

Answers (5)

Yahia
Yahia

Reputation: 70369

Not sure whate you are asking but they are different:

default(T) returns null if T isn't a value type... the CreateInstance call creates an instance and calls the default constructor if there is one (otherwise an exception is thrown)...

Upvotes: 2

vcsjones
vcsjones

Reputation: 141638

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.

Upvotes: 19

Tomas Vana
Tomas Vana

Reputation: 18775

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.

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190945

default(T) will return null for reference types. Activator.CreateInstance<T>() will not. A string is a reference type in .NET.

Upvotes: 2

cdhowie
cdhowie

Reputation: 169008

They will always return a different result when T is a reference type. default(T) will return null, while Activator.CreateInstance<T>() will return a new instance of T, created using T's public parameterless constructor.

Upvotes: 3

Related Questions