The problem is very simple and basic.
At runtime, I want to be able to get the default value of a specific type.
One solution is to use reflection and create a new instance of the object. But in this case you would use reflection more than one.
Let's analyze the problem. There two group of types that we could have: Value Type and Reference Type. For Reference type the solution is very simple, because we need all the time to return NULL. For Value Type we can use Activator class to create a new instance of our type.
Another thing that we can do at this level is to cache the default value for Value Type, once we found them. In this way we don't need to call activator multiple times.
At runtime, I want to be able to get the default value of a specific type.
One solution is to use reflection and create a new instance of the object. But in this case you would use reflection more than one.
Let's analyze the problem. There two group of types that we could have: Value Type and Reference Type. For Reference type the solution is very simple, because we need all the time to return NULL. For Value Type we can use Activator class to create a new instance of our type.
public static class TypeExtension
{
public static object GetDefaultValue(this Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
Assert.AreEqual(0,typeof(int).GetDefaultValue());
Assert.AreEqual(default(decimal), typeof(decimal).GetDefaultValue());
Assert.AreEqual(null, typeof(string).GetDefaultValue());
For this purpose I created an extension methods that returns the default value.Another thing that we can do at this level is to cache the default value for Value Type, once we found them. In this way we don't need to call activator multiple times.
public static class TypeExtension
{
private static HybridDictionary defaultValueMap = new HybridDictionary();
public static object GetDefaultValue(this Type type)
{
if (!type.IsValueType)
{
return null;
}
if (defaultValueMap.Contains(type))
{
return defaultValueMap[type];
}
object defaultValue = Activator.CreateInstance(type);
defaultValueMap[type] = defaultValue;
return defaultValue;
}
}
Enjoy!
Hi Radu
ReplyDeleteassuming you had compile time knowledge of the type you could use generics
public static T GetDefault()
{
return default(T);
}
static void Main(string[] args)
{
Console.WriteLine(GetDefault());
Console.WriteLine(GetDefault());
Console.WriteLine(GetDefault());
Console.WriteLine(GetDefault());
Console.WriteLine(GetDefault());
}
Yes, this works great for cases where you know at compile time the type. For a case like a generic serialization class, that knows at runtime the type of an object this would not work.
Delete