c# - How do you get a variable's name as it was physically typed in its declaration?

Posted by Petras on Stack Overflow See other posts from Stack Overflow or by Petras
Published on 2009-04-04T02:51:55Z Indexed on 2010/04/19 1:13 UTC
Read the original article Hit count: 318

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about variable