Monday, January 28, 2013

Getting rid of magic strings that point at PropertyNames

Often times, you end up with code that includes magic strings that point at property names of a class. I hate this, because it normally ends up causing runtime errors instead of compile time errors.

While working with Asp.Net MVC, I found that you could pass properties to helper methods (such as Html.TextBoxFor) and it would automagically figure out the name of the property and use it to build out the ID and Name fields of the html object. I wanted something similar to that and here is my code:

//The helper class that provides the “GetPropertyName” method
public static class ReflectionHelper
{
    public static string GetPropertyName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        MemberExpression body = (MemberExpression) expression.Body;
        return body.Member.Name;
    }
}

//A test class to test what we are doing
public class Test
{
    public string Name{get;set;}
}

//A simple test
void Main()
{
    Test t = new Test();
    Console.WriteLine(t.GetPropertyName(m => m.Name));
}

No comments: