ExpressionTree-While

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 n = 6;
		var cResult = 1;
		while (n > 1)
		{
		    cResult = cResult * n;
		    n--;
		}
		Console.WriteLine(cResult);
		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
		var nArgument = Expression.Parameter(typeof(int), "n");
		var result = Expression.Variable(typeof(int), "result");

		// Creating a label that represents the return value
		LabelTarget label = Expression.Label(typeof(int));

		var initializeResult = Expression.Assign(result, Expression.Constant(1));

		// This is the inner block that performs the multiplication,
		// and decrements the value of 'n'
		var ifTrueBlock = Expression.Block(
		    Expression.Assign(result,
		        Expression.Multiply(result, nArgument)),
		    Expression.PostDecrementAssign(nArgument)
		);

		var ifThenElseExpr = Expression.IfThenElse(
		    Expression.GreaterThan(nArgument, Expression.Constant(1)),
		    ifTrueBlock,
		    Expression.Break(label, result)
		);

		// Creating a method body.
		BlockExpression body = Expression.Block(
		    new[] { result },
		    initializeResult,
		    Expression.Loop(ifThenElseExpr, label)
		);

		// Compile and run an expression tree.
		var factorial = Expression.Lambda<Func<int, int>>(body, nArgument).Compile();

		Console.WriteLine(factorial(6));
		
 
	}
}
;