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?
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!
They are entirely different.
default(T)
, whenT
is 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
.
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 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.
default(T)
will return null
for reference types. Activator.CreateInstance<T>()
will not. A string
is a reference type in .NET.
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)...
精彩评论