ExpressionTree-Goto

CSharp · Console

/Program.cs

using System;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("****************** C# Equivalent Output **************************\n\n");
		
		Console.WriteLine("First Statment");
		
        goto JumpTo;
		
        Console.WriteLine("Second  Statment");
        
		JumpTo:
		
        Console.WriteLine("Third Statment and Second Statment is skiped");

		
		Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
		
		// A label expression of the void type that is the target for the GotoExpression.
        LabelTarget JumpTo = Expression.Label();

        // This block contains a GotoExpression.
        // It transfers execution to a label expression that is initialized with the same LabelTarget as the GotoExpression.
        // The types of the GotoExpression, label expression, and LabelTarget must match.
        BlockExpression blockExpr = Expression.Block(
                WriteLineExpression("First Statment"),
                Expression.Goto(JumpTo),
                WriteLineExpression("Second  Statment"),
                Expression.Label(JumpTo),
                WriteLineExpression("Third Statment and Second Statment is skiped")
            );

        // The following statement first creates an expression tree,
        // then compiles it, and then runs it.
        Expression.Lambda<Action>(blockExpr).Compile()();

	}

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

}
;