1

let's say I have a var,

string variableName = "hello world";

How can I get the name of my variable and not it's value?

string x = variableName.name();

//x = "variableName"
Ido Barnea
  • 142
  • 2
  • 13
  • 1
    If you need the name of a variable, probably you have something wrong in your project – Marco Salerno Jan 21 '20 at 16:27
  • 1
    You do realize that your example of making `x = "hello"` is accomplished by just regular programming (`var x = var;`)? (best not to use keywords for your variable names!) – Fixation Jan 21 '20 at 16:28

1 Answers1

3

You can use

var name = nameof(x);

to get "x" in a string named "name", where x is the variable you want.

However, it will only work with modern flavours of C#. For older ones, you'll have to use Expression, which is a PITA, both for performances and in terms of code complexity for a such simple need.

edit : more details here : get name of a variable or parameter

AFract
  • 8,868
  • 6
  • 48
  • 70