Expression.Default in .NET 3.5

How can I emulate Expression.Default

(new in .NET 4.0) in 3.5?

Do I need to manually check the type of the expression and use different code for references and value types?

This is what I am doing now, is there a better way?

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

      

+2


a source to share


2 answers


How did you do it, good. There is no Type.GetDefaultValue () method built into the .NET Framework, as you would expect, so special message handling for value types is needed.

It is also possible to create 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 created only once, when the expression tree is first created, rather than every time the expression is evaluated. But that's nothing.

+2


a source


How do I use 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);
        }
    } 
}

      

0


a source







All Articles