Sunday, January 17, 2010

Using Expression Tree in C#

Hi All,

In my previous post i have explained the solution how to work around the Reflections to access the Property of class object. By analyzing code with different scenario my solution of Reflections get fails in case of ProeprtyName changed ( i.e suppose your User class previous have Surname afterword changed it with Lastname).

By digging more features availabes in .net framework i come up with the solution of using the Expression Tree instead of Reflections.

The Expression Tree classes are implemented in System.Query.dll and their namespace System.Linq.Expressions(might be change as product matures).

So say for example below is my sample class, with two property "FirstName" and "LastName"

    8 public class ExpressionTest

    9 {

   10     public string FirstName { get; set; }

   11     public string LastName { get; set; }

   12 }



and i want to show the name of property in my console application, so before that i will introduce the Expression Tree usage in this scenerio,

   13 public static string GetName<T>(Expression<Func<T>> e)

   14     {

   15         var member = (MemberExpression)e.Body;

   16         return member.Member.Name;

   17     }



Now to call this method and get the names of class properties we defined above we can call the Lambda Expression as given,

   18 ExpressionTest testsample = new ExpressionTest();

   19     Console.WriteLine("{0}", GetName(() => testsample.FirstName));

   20     // prints FirstName



So here is area of interest is utilization of Expression Tree classes with help of C# 3.0 onwards.

Happy Coding :)

No comments:

Post a Comment