I would like to know if the below statements ever return a different result for reference types, or are they identical?
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!
They are entirely different.
default(T), whenTis a reference type, will always benull.Activator.CreateInstance<T>()will create a new instance of that type using the default constructor if present, otherwise, throwsMissingMethodException.