C# – How to get a variable’s name as it was physically typed in its declaration?

creflectionvariables

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

The class below contains the field city.

I need to dynamically determine the field's name as it is typed in the class declaration
i.e. I need to get the string "city" from an instance of the object city.

I have tried to do this by examining its Type in DoSomething() but can't find it when examining the contents of the Type in the debugger.

Is it possible?

public class Person
{
  public string city = "New York";

  public Person()
  {
  }


  public void DoSomething()
  {
    Type t = city.GetType();

    string field_name = t.SomeUnkownFunction();
    //would return the string "city" if it existed!
  }
}

Some people in their answers below have asked me why I want to do this.
Here's why.

In my real world situation, there is a custom attribute above city.

[MyCustomAttribute("param1", "param2", etc)]
public string city = "New York";

I need this attribute in other code.
To get the attribute, I use reflection.
And in the reflection code I need to type the string "city"

MyCustomAttribute attr;
Type t = typeof(Person);

foreach (FieldInfo field in t.GetFields())
{

  if (field.Name == "city")
  {
    //do stuff when we find the field that has the attribute we need
  }

}

Now this isn't type safe.
If I changed the variable "city" to "workCity" in my field declaration in Person this line would fail unless I knew to update the string

if (field.Name == "workCity")
//I have to make this change in another file for this to still work, yuk!
{
}

So I am trying to find some way to pass the string to this code without physically typing it.

Yes, I could declare it as a string constant in Person (or something like that) but that would still be typing it twice.

Phew! That was tough to explain!!

Thanks

Thanks to all who answered this * a lot*. It sent me on a new path to better understand lambda expressions. And it created a new question.

Best Answer

Maybe you need this. Works fine.

I found this here.

static void Main(string[] args)
{
    var domain = "matrix";
    Check(() => domain);
    Console.ReadLine();
}

static void Check<T>(Expression<Func<T>> expr)
{
    var body = ((MemberExpression)expr.Body);
    Console.WriteLine("Name is: {0}", body.Member.Name);
    Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)
   .GetValue(((ConstantExpression)body.Expression).Value));
}

Output will be:

Name is: 'domain'
Value is: 'matrix'