开发者

How can I call default(T) with a type? [duplicate]

This question already has answers here: Programmatic equivalent of default(Type) (14 answers) Closed 9 years ago.

In c# I can use default(T) to get the default value of a type. I need to get the default type at run time from a System.Type. How can I do this?

E.g. Something along the lines of this (which doesn't work)

var type = typeof(int);
var defaultValue = de开发者_JAVA技巧fault(type);


For a reference type return null, for a value type, you could try using Activator.CreateInstance or calling the default constructor of the type.

public static object Default(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }

   return null;
}


If you're trying to build an expression tree, use Expression.Default:

Expression expression = Expression.Default(type);

One other way you could do this fairly easily would be:

object defaultValue = Array.CreateInstance(type, 1).GetValue(0);

Ugly, but it'll work :) Note that it's hard to get the default value of a nullable type, as it will always be boxed to a null reference.

As noted in comments, there are some obscure scenarios (void and pointer types) where these aren't equivalent, but they're corner cases :)


That's pretty easy, you just have 2 cases to consider:

  • reference types: the default value is always null
  • value types: you can easily create an instance using Activator.CreateInstance

    public static object GetDefaultValue(Type type)
    {
        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        else
        {
            return null;
        }
    }
    

You could also consider using FormatterServices.GetUninitializedObject instead of Activator.CreateInstance, it's probably faster.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜