How can I call default (T) with type?

In C #, I can use default(T)to get the default value for a type. I need to get the default type at runtime from System.Type. How can i do this?

eg. Something like this (which doesn't work)

var type = typeof(int);
var defaultValue = default(type);
+5
source share
3 answers

For a return reference type nullfor a value type, you can try to use Activator.CreateInstanceor call the default constructor for the type.

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

   return null;
}
+9
source

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

Expression expression = Expression.Default(type);

Another way you could do this quite easily would be:

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

, :) , NULL, .

, (void ), , :)

+6

, 2 :

  • : null
  • : , Activator.CreateInstance

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

FormatterServices.GetUninitializedObject Activator.CreateInstance, , .

+3

All Articles