-1

Possible Duplicate:
How to get variable name using reflection?

How to get the string name's name not the value of the string

string MyString = "";
Response.Write(MyString.GetType().Name);//Couldn't get the string name not the value of the string

The result should display back the string name "MyString"

I've found some suggested codes and rewrite it to make it shorter but still didn't like it much.

static string VariableName<T>(T item) where T : class
{
    return typeof(T).GetProperties()[0].Name;
}

Response.Write(VariableName(new { MyString })); I am looking another way to make it shorter like below but didn't how to use convert the current class so i can use them in the same line

  Response.Write( typeof(new { MyString }).GetProperties()[0].Name);
Community
  • 1
  • 1
SMTPGUY01
  • 135
  • 2
  • 8

1 Answers1

0

While Marcelo's answer (and the linked to "duplicate" question) will explain how to do what you're after, a quick explanation why your code doesn't work.

GetType() does exactly what it says: it gets the Type of the object on which it is called. In your case, it will return System.String, which is the Type of the object referenced by your variable MyString. Thus your code will actually print the .Name of that Type, and not the name of the variable (which is what you actually want.)

dlev
  • 48,024
  • 5
  • 125
  • 132
  • I've made the class to be a lot shorter but I don't really like it much. static string VariableNameName(T item) where T : class { return typeof(T).GetProperties()[0].Name; } ///Here is how to use it var MyString = ""; Response.Write(VariableNameName(new { MyString })); I wanted to make it shorter like the following but don't know how to use this LINQ yet. Response.Write( typeof(new { MyString }).GetProperties()[0].Name); – SMTPGUY01 Jun 20 '11 at 03:45