Fun with .net: Programmatically determine variable name

1. March 2010

This is the second in a series of blog posts high lighting interesting snippets hacks I have run across. Although these do work, I do not recommend trying them in production code.

Have you ever re-factored some code, only to find out that you missed a place were a variable name was referred to in a string? Let’s say you were checking the input of a method, and throw an exception if it was out of bounds.

if (string.IsNullOrEmpty(someInput))
{
    throw new ArgumentNullException("someInput");
}

 

With this trick, you will never have to worry about forgetting to update the ArgumentNullException when you change the parameter name. It will programmatically determine the variable name for you!

void CheckInput(string someInput)
{
    if (string.IsNullOrEmpty(someInput))
    {
        //do not do this...ever!
        string varName = NameOfVariable(() => someInput);
        throw new ArgumentNullException(varName);
    }
}

string NameOfVariable(Expression<Func<object>> expressionTree)
{
    return ((MemberExpression)expressionTree.Body).Member.Name;
}

 

Ok, ok…so this falls apart fast, and I feel dirty for even sharing.  Just don’t use this in production…Or anywhere for that matter!


short link to this post:

.net, Fun with .net ,

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading