Mar
1
2010

Fun with .net: Programmatically determine variable name

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!

Add comment




biuquote
Loading


AdSense

Software engineer by hobby and trade. When I am not sitting in front of a computer, you can find me playing with my kids. I am lucky enough to be married to my best friend and high school sweetheart. Life couldn't be better!

 

All content is mine, not my employers

Chronology

Tweets

what is the easiest way to *just* the last changeset number from git?
21 hours ago via Silver Bird
@ParasValecha so it is a virus some marketing guy manage to win an award for? ;)
3 days ago via Silver Bird
@ParasValecha none. I think they are one of the worse "viruses" you can get. Thrashing your disk and hogging CPU any chance they get
3 days ago via Silver Bird
...i have gone 5 years without one and been fine
3 days ago via Microsoft
... and provide little value on a day to day basis. Don't go to random content, and don't open stuff you don't understand...
3 days ago via Microsoft
I wholeheartedly believe that virus scanners are one of the worst things to install. they really slow down your computer...
3 days ago via Microsoft
RT @CodeWisdom: "When your hammer is C++, everything begins to look like a thumb." - Steve Haflich #fb
5 days ago via rowi for Windows Phone
Follow me on Twitter