ExpressionTree-GetterSetter

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("***************** Setter Output **************************\n\n");
        
		var setterNameProperty = ExpressionUtils.CreateSetter<Employee, string>("Name");
		var setterBirthDateProperty = ExpressionUtils.CreateSetter<Employee, DateTime>("BirthDate");

		Employee emp = new Employee();

		setterNameProperty(emp, "John");
		setterBirthDateProperty(emp, new DateTime(1990, 6, 5));

		Console.WriteLine("Name: {0}, DOB: {1}", emp.Name, emp.BirthDate);

		
		Console.WriteLine("\n\n***************** Getter Output **************************\n\n");
		
		var getterNameProperty = ExpressionUtils.CreateGetter<Employee, string>("Name");
    	var getterBirthDateProperty = ExpressionUtils.CreateGetter<Employee, DateTime>("BirthDate");
    
    	Employee emp1 = new Employee()
    	{
    	    Name = "John",
    	    BirthDate = new DateTime(1990, 6, 5)
    	};
    
    	var name = getterNameProperty(emp1);
    	var birthDate = getterBirthDateProperty(emp1);
    
    	Console.WriteLine("Name: {0}, DOB: {1}", name, birthDate);	
	}
}

public class Employee
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

public static class ExpressionUtils
{
    public static Action<TEntity, TProperty> CreateSetter<TEntity, TProperty>(string name) where TEntity: class
    {
        PropertyInfo propertyInfo = typeof(TEntity).GetProperty(name);

        ParameterExpression instance = Expression.Parameter(typeof(TEntity), "instance");
        ParameterExpression propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");

		var body = Expression.Assign(Expression.Property(instance, name), propertyValue);

        return Expression.Lambda<Action<TEntity, TProperty>>(body, instance, propertyValue).Compile();
    }

    public static Func<TEntity, TProperty> CreateGetter<TEntity, TProperty>(string name) where TEntity: class
    {
        ParameterExpression instance = Expression.Parameter(typeof(TEntity), "instance");

        var body = Expression.Property(instance, name);

        return Expression.Lambda<Func<TEntity, TProperty>>(body, instance).Compile();
    }
}
;