Diego Mijelshon
Diego Mijelshon

Reputation: 52745

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

Upvotes: 2

Views: 495

Answers (2)

luksan
luksan

Reputation: 7767

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.

Upvotes: 2

Simon Chadwick
Simon Chadwick

Reputation: 1148

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

Upvotes: 0

Related Questions