Monday, February 22, 2010

Expression trees

Howto get the name of a property or class. To minimize magic strings

Usage:
// This code will return "MyProperty".
ObjectHelper.GetMemberName(() => someEntity.MyProperty);

        using System;
using System.Linq.Expressions;
/// 
/// Extensions to object class
/// 
public static class ObjectHelper
{
/// 
/// Gets the name og the property og class using Expression trees
/// 
/// 
/// The expression to get name for
/// 
/// 
/// Type of the object
/// 
/// 
/// A string with the name, or an exception if it isn't a member expression
/// 
/// 
/// 
private static string GetMemberName(Expression> e)
{
var member = e.Body as MemberExpression;
// If the method gets a lambda expression
// that is not a member access,
// for example, () => x + y, an exception is thrown.
if (member == null)
{
throw new ArgumentException(
"'" + e +
"': is not a valid expression for this method");
}
return member.Member.Name;
}
}
Share:

0 kommentarer:

Post a Comment