开发者

default(T) versus Activator.CreateInstance(T)

开发者 https://www.devze.com 2023-03-31 13:57 出处:网络
I would like to know if the below statements ever return a different result for reference types, or are they identical?

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!


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.


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)...

0

精彩评论

暂无评论...
验证码 换一张
取 消