.NET C# Extension Methods - Reflection

Sunday, November 22, 2009

.NET C# Extension Methods - Reflection

Other extension methods:

---------------------------

I was wondering how to get the name of a property via reflection. So I searched the Internet and I found this on Google code. The code was not good enough though. I was not able to get a string name from level 3 (i.e: User.Name.First). I did a small modifications and ended with this class that works perfect.

    /// <summary>
/// An extentension method on an actual object to get its member names
/// </summary>
public static class ReflectionExtensions
{
public static string MemberName<T, R>( this T obj, Expression<Func<T, R>> expr )
{
var node = expr.Body as MemberExpression;
if( object.ReferenceEquals( null, node ) )
throw new InvalidOperationException( "Expression must be of member access" );
return node.Member.Name;
}
}

/// <summary>
/// If we don't have an actual object we can still refer to its type with this generic static class
/// </summary>
public static class MembersOf<T>
{
public static string GetName<R>( Expression<Func<T, R>> expr )
{
var node = expr.Body as MemberExpression;
if( object.ReferenceEquals( null, node ) )
throw new InvalidOperationException( "Expression must be of member access" );

string result = BuildName( node, sb );

sb.Remove( 0, sb.Length );
temp.Remove( 0, temp.Length );

return result.Remove( result.Length-1 );
}

private static StringBuilder sb = new StringBuilder();
private static StringBuilder temp = new StringBuilder();
private static string BuildName( MemberExpression expr, StringBuilder sb )
{
if( expr.IsNotNull() )
{
temp.Append( expr.Member.Name );
temp.Append(".");

sb.Insert( 0, temp.ToString() );
temp.Remove( 0, temp.Length );

BuildName( expr.Expression as MemberExpression, sb );
}

return sb.ToString();
}
}

Now the question is where this code can be handy? I use this when I want to build NHibernate Criteria or DetachedCriteria. When you create a Criteria you use a code like this one:


ICriteria crit = session.CreateCriteria(typeof(Customer));
crit.Add(Expression.Eq("Customer.Name.First", someValue));

Here the Name property is a NHibernate component. The problem is that if you change the property Name to FirstName you will not get a compile error but you will get runtime error when the query is executed against the database. Also you can use some refactoring tool like RefactorPro! and the changes in the component will be applied also in the criteria. Nice, ahh?!? And the code above will be:


ICriteria crit = session.CreateCriteria(typeof(Customer));
crit.Add(Expression.Eq(MembersOf<Customer>.GetName(x=>x.Name.First), someValue));


No comments:

Post a Comment