How can I emulate Expression.Default (new in .NET 4.0) in 3.5?
Do I need to manually check the expression type and use different code for reference and value types?
This is what I’m currently doing, is there a better way?
Expression GetDefaultExpression(Type type)
{
if (type.IsValueType)
return Expression.New(type);
return Expression.Constant(null, type);
}
The way you did it is good. There is no Type.GetDefaultValue() method built in to the .NET Framework as one would expect, so the special case handling for value types is indeed necessary.
It is also possible to produce a constant expression for value types:
The advantage of this I suppose would be that the value type is only instanciated once, when the expression tree is first built, rather than every time the expression is evaluated. But this is nitpicking.