ExpressionTree-Switch

CSharp · Console

/Program.cs

using System;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		
		Console.WriteLine("****************** C# Equivalent Output **************************\n\n");
		int value = 4;

		switch (value)
		{
		    case 1:
		        Console.WriteLine("First Case");
		        break;
		    case 2:
        		Console.WriteLine("Second Case");
		        break;
		    case 3:
		        Console.WriteLine("Third Case");
		        break;
		    default:
		        Console.WriteLine("Default Case");
		        break;
		}
		
		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
 
		ConstantExpression switchValue = Expression.Constant(4);

		var defaultCase = WriteLineExpression("Default Case");
		var case1 = WriteLineExpression("First Case");
		var case2 = WriteLineExpression("Second Case");
		var case3 = WriteLineExpression("Third Case");

		// This expression represents a switch statement 
		// that has a default case.
		SwitchExpression switchExpr =
		    Expression.Switch(
		        switchValue,
		        defaultCase,
		        new SwitchCase[]
		        {
		            Expression.SwitchCase(case1,Expression.Constant(1)),
		            Expression.SwitchCase(case2,Expression.Constant(2)),
		            Expression.SwitchCase(case3,Expression.Constant(3))
		        }
		    );

		Expression.Lambda<Action>(switchExpr).Compile()();
	}
	
	public static Expression WriteLineExpression(string s)
	{
    	return Expression.Call(null,
        	typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
        	Expression.Constant(s));
	}
}
;