Resolving a parameter name at runtime

xyz picture xyz · May 15, 2009 · Viewed 13.2k times · Source

Possible Duplicate:
Finding the Variable Name passed to a Function in C#

In C#, is there a way (terser the better) to resolve the name of a parameter at runtime?

For example, in the following method, if you renamed the method parameter, you'd also have to remember to update the string literal passed to ArgumentNullException.

    public void Woof(object resource)
    {
        if (resource == null)
        {
            throw new ArgumentNullException("resource");
        }

        // ..
    }

Answer

Justin Ethier picture Justin Ethier · May 15, 2009

One way:

static void Main(string[] args)
{
  Console.WriteLine("Name is '{0}'", GetName(new {args}));
  Console.ReadLine();
}

This code also requires a supporting function:

static string GetName<T>(T item) where T : class
{
  var properties = typeof(T).GetProperties();
  Enforce.That(properties.Length == 1);
  return properties[0].Name;
}

Basically the code works by defining a new Anonymous Type with a single Property consisting of the parameter who's name you want. GetName() then uses reflection to extract the name of that Property.

There are more details here: http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html