ExpressionTree-PropertyOrField

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq.Expressions;

public class TestClass
{
    public int myProperty {get; set;}
	public int myField = 50;
}

public class Program
{
    public static void Main(string[] args)
    {
		TestClass obj = new TestClass();
		obj.myProperty = 60;
		
        Console.WriteLine("****************** C# Equivalent Output **************************\n\n");

		Console.WriteLine("Property: {0}",obj.myProperty);
		Console.WriteLine("Field: {0}",obj.myField);

        Console.WriteLine("\n\n***************** Expression Tree Output **************************\n\n");
		
		Expression propertyExpr = Expression.PropertyOrField(
            Expression.Constant(obj),
            "myProperty"
        );
		

        Expression fieldExpr = Expression.PropertyOrField(
            Expression.Constant(obj),
            "myField"
        );
		
		Console.WriteLine("Property: {0}",Expression.Lambda<Func<int>>(propertyExpr).Compile()());
        Console.WriteLine("Field: {0}",Expression.Lambda<Func<int>>(fieldExpr).Compile()());
    }
}
;