Joel Holder

Math, coding, philosophy, art, and other things that interest me

View on GitHub
13 March 2011

Property getter/setter extraction from C# Types

by Joel Holder

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 GetPropertyFunction(this Type source, string name)
          {
             ParameterExpression param = Expression.Parameter(typeof(X), "arg");
             MemberExpression member = Expression.Property(param, name);
             LambdaExpression lambda = Expression.Lambda(typeof(Func), member, param);
             Func compiled = (Func)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.GetPropertyFunctionTestObject, String>("Name");
             String value = getName(testObj);

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