Property getter/setter extraction from C# Types

The C# Expression API allows you to scrape property and method definitions from Types and work with them as external references.  See here:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Dynamic;
using System.Runtime.CompilerServices;

public static class Extensions

 {
       public static Func<X, T> GetPropertyFunction<X, T>(this Type source, string name)
          {
             ParameterExpression param = Expression.Parameter(typeof(X), "arg");
             MemberExpression member = Expression.Property(param, name);
             LambdaExpression lambda = Expression.Lambda(typeof(Func<X, T>), member, param);
             Func<X, T> compiled = (Func<X, T>)lambda.Compile();
             return compiled;
         }
}

 

And you can use it like this:


[TestMethod]
public void TestMethod1()
         {
             var testObj = new TestObject
             {
                 ID = 1,
                 Description = "ASDFASDF",
                 Name = "GGGG",
                 UnitPrice = 6
             };

             Type type = typeof(TestObject);
             var getName = type.GetPropertyFunction<TestObject, String>("Name");
             String value = getName(testObj);

             Assert.IsTrue(value == testObj.Name);
       }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: