Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 = default(type);
like image 563
John Mills Avatar asked Sep 14 '10 08:09

John Mills


1 Answers

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;
}
like image 72
Julien Hoarau Avatar answered Oct 19 '22 11:10

Julien Hoarau