After Thought

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.

Advertisements

Written by shashankshetty

March 21, 2009 at 2:44 pm

7 Responses

Subscribe to comments with RSS.

  1. […] to VoteMagic Strings O Magic Strings (3/21/2009)Saturday, March 21, 2009 from shashankshettyI guess we all agree that magic strings in code become […]

  2. Hi,

    I’m pretty sre you will get a cast error on line 2 of your code if UserId is not a string, which it usually isn’t. I was playing around with this the other day and had the same issue. Do you get this problem?

    Adam

    Adam

    March 23, 2009 at 12:51 am

  3. Thats a good point Adam. In the above example I assumed UserId to be a string. I have now extended the post by adding a GetPropertyName method that can handle data types other than string.

    shashankshetty

    March 23, 2009 at 5:09 am

  4. This solution is really smart, thanks !
    I’ve just test it in VB.net like this :

    Public Shared Function GetPropertyName(Of T, R)(ByVal expression As Expression(Of Func(Of T, R))) As String
    Dim memberExpression As MemberExpression = DirectCast(expression.Body, MemberExpression)
    Return (memberExpression.Member.Name)
    End Function

    GetPropertyName(Function(user As User) user.Options)

    uglyrabbit

    June 18, 2009 at 10:00 am

  5. Very nice solution !!! Can you tell me how you can handle an Int or other type ?

    HoangPham

    August 12, 2009 at 11:37 am

    • HoangPham,

      If you want a generic solution to get the PropertyName then you can use this.

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

      shashankshetty

      August 18, 2009 at 10:21 am

      • Hi shashankshetty,

        Great !!! Thanks for your response.

        HoangPham

        September 8, 2009 at 3:09 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: