Getting the default value for a Type

Sometimes we need to get a default value for an specific type but we only know the type in runtime, then we can not use default(T). One way to do this is to use a simple extension method:

public static object DefaultValue(this Type type)
{
    return Expression.Lambda(Expression.Default(type)).Compile().DynamicInvoke();
}

As you can see it is a simple Expression tree that returns the default value for the type.

No Comments