ExpressionTree-IfThen

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 num = 60;

		if(num > 10)
		{
    		Console.WriteLine("num is greater than 10");
		}
		
		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
		var testCondition = Expression.Constant(num > 10);
		var ifTrueBlock = WriteLineExpression("num is greater than 10");
		var ifThenExpr = Expression.IfThen(testCondition, ifTrueBlock);

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

}
;