3

greetings, could you please help? i need to get a variable (name) in string format. for example below i need to display "test" as string.

        int test = 69;
        //below does not work
        MessageBox.Show((string)test);
        // below works but displays the int value
        MessageBox.Show(test.ToString());

thank you for your time.

well i have an enum:

    public enum ShipOrientation
    {
        North,
        East,
        South,
        West
    }

and i do some processing based on direction and if int North then apply enum North direction.

1
  • "then apply enum direction" - what do you mean? Can you give a full sample that includes the variables that you wish to string-ize? Commented Feb 22, 2010 at 13:59

2 Answers 2

5

not for variables, but if you promote your variable to a property on the class, you can use Expressions to achieve this.

good sample here

Sign up to request clarification or add additional context in comments.

2 Comments

And also you may use Reflection to retrieve member names. msdn.microsoft.com/en-us/library/…
generally the reflection approach would need a string as input to find the property
3

This cannot be done normally - variable names are compiled out in C#.

On the other hand, if you can write the variable's name, you can just place quotation marks around it and treat it as a string.

Assuming that's not good enough for your scenario, there are a few hacks that can let you do something almost like this; but their usefulness kind of depends on what you're trying to do - why do you need to variable's name?

2 Comments

Actually, this can be done, but the code is very hackish: msmvps.com/blogs/jon_skeet/archive/2009/12/09/…
Yes, I realize: that's one of the hacks I'm referring to. At that point, you're no longer working with variables, but on type members - which can be reflected upon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.