After Thought

Posts Tagged ‘Static Reflection

Magic Strings O Magic Strings

with 7 comments

I guess we all agree that magic strings in code become very annoying to maintain in the long run.  Some of the instances where you can be using magic strings is if you are trying to get the property name using reflection

typeOf(User).GetProperty(“UserId”)

or create a Html TextBox in asp.net MVC

<%= Html.TextBox(“UserId”) %>

Enter Static Reflection to relieve us from using the quoted text or magic strings. Let us try to get the propertyname UserId in the User class below without using magic string “UserId” in the code.

public class User
{
  public string UserId { get; set; }
}

We can do this using normal reflection as shown in the beginning of this post or as shown below:

Expression expression = (User user) => user.UserId;
MemberExpression memberExpression = (MemberExpression)expression.Body;
Console.WriteLine(memberExpression.Member.Name);

You can enclose the 3 lines of code above in a method named GetPropertyName.

public static string GetPropertyName<T>(Expression<Func<T, string>> expression)
{
	MemberExpression memberExpression = (MemberExpression)expression.Body;
	return memberExpression.Member.Name;
}

You can now get the property name just by calling the method

GetPropertyName((User user) => user.UserId).

By not using  “UserId” in the code, we have eliminated any chances of rename accidents or any chance of missing the usage of the property when you do Find Usages. This post by Clinton Sheppard gives more detail on the topic.

Written by shashankshetty

March 21, 2009 at 2:44 pm