I\'m using reflection to loop through a Type
\'s properties and set certain types to their default. Now, I could do a switch on the type and set the defau
If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an Expression, compile and run it on-the-fly.
The following extension method will take a Type and get the value returned from default(T) through the Default method on the Expression
class:
public static T GetDefaultValue()
{
// We want an Func which returns the default.
// Create that expression here.
Expression> e = Expression.Lambda>(
// The default value, always get what the *code* tells us.
Expression.Default(typeof(T))
);
// Compile and return the value.
return e.Compile()();
}
public static object GetDefaultValue(this Type type)
{
// Validate parameters.
if (type == null) throw new ArgumentNullException("type");
// We want an Func
You should also cache the above value based on the Type
, but be aware if you're calling this for a large number of Type
instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.