Thursday, October 22, 2009

Expression Trees .NET 4.0 Part 2

In my previous post I showed an example of some of the new extensions that were added to the Expression Tress in .NET 4.0.  In this post I will show you how to create a simple Switch/Case Expression.  So in that case I will be passing two integers to the expression and then using an Expression.Switch expression which will decide whether the values are equal or not.  So here is the method code:

private static string CompareIntegersForEqualitySwitch(int value1, int value2)
{
    var result = Expression.Variable(typeof(string), "result");
    var inputValue1 = Expression.Parameter(typeof(int), "inputValue1");
    var inputValue2 = Expression.Parameter(typeof(int), "inputValue2");

    var compare = Expression.Lambda<Func<int, int, string>>
        (
            Expression.Block
            (
                new[] { result },
                Expression.Block
                (
                    Expression.Assign
                    (
                        result,
                        Expression.Constant(String.Empty)
                    )
                ),
                Expression.Block
                (
                    Expression.Switch
                    (
                        inputValue1,
                        Expression.Assign(result, Expression.Constant("Not Equal")),//default body
                        new []
                        {
                            Expression.SwitchCase(Expression.Assign(result, Expression.Constant("Equal")), new [] {inputValue2})
                        }
                    )
                ),
                result
            ),
            inputValue1,
            inputValue2

        ).Compile();

    return compare(value1, value2);

}

The points of interest here are:

1.  Expression.Switch which is the starting point/expression of the switch statement.  The first expression (inputValue1) is an Expression.Parameter that contains the integer that we will be testing for equality.

2.  There is a default body expression which in this case is returning “Not Equal” as result.

3.  There is an array of Expression.SwitchCase that contains all possible case statements and assigns the appropriate value to the result Expression.Variable.  Of course, if none of those case statements is valid, the default statement will be valid.

I am not a smoker and this is the SmokingCode!

No comments:

Post a Comment