Sunday, January 17, 2010

Handling Exceptions in Using Expression Tree in C#

Hi All,

In my previous post i have explained how we can work with Expression Tree to access the Properties easily. The major consideration which we have to take here using Lambda Expressions is Expressions are failed if inputs are given wrong.

So here with this post i come up with the solution of Manage possible Exceptions, I have made some corrections in my previous post method named "GetName".

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

    9 {

   10     var member = e.Body as MemberExpression;

   11 

   12     // If the method gets a lambda expression

   13     // that is not a member access,

   14     // for example, () => FirstName + LastName, an exception is thrown.

   15     if (member != null)

   16         return member.Member.Name;

   17     else

   18         throw new ArgumentException(

   19             "'" + e +

   20             "': is not a valid expression for this method");

   21 }



Now code looks safer to show proper exception whenever wrong inputs are given to it.

Happy Coding :)

No comments:

Post a Comment