I would like to know if the below statements ever return a different result for reference types, or are they identical?
default(T)
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!
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.
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.
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.
They are entirely different.
default(T)
, when T
is a reference type, will always be null
.Activator.CreateInstance<T>()
will create a new instance of that type using the default constructor if present, otherwise, throws MissingMethodException
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With