tags:

views:

90

answers:

2

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);
}
A: 

How about using an extension method?

using System;
using System.Linq.Expressions;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(int);
            Expression e = t.Default(); // <-----
            Console.WriteLine(e);
            t = typeof(String);
            e = t.Default();            // <-----
            Console.WriteLine(e);
            Console.ReadLine();
        }
    }

    public static class MyExtensions
    {
        public static Expression Default(this Type type)
        {
            if (type.IsValueType)
                return Expression.New(type);
            return Expression.Constant(null, type);
        }
    } 
}
Simon Chadwick
Well, that's just the same but with a `this` qualifier :-) I was wondering if there was a better way (guess not)
Diego Mijelshon
+1  A: 

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:

Expression GetDefaultExpression(Type type) 
{ 
    if (type.IsValueType) 
        return Expression.Constant(Activator.CreateInstance(type), type); 
    return Expression.Constant(null, type); 
} 

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.

luksan
I like the optimization, no matter how small :-)
Diego Mijelshon