-1

The following code prints "argument".

void PrintNameOf(string argument)
{
    Console.WriteLine($"{nameof(argument)} has value: {argument}");
}

string myString = "hello";
PrintNameOf(myString);

Is there a way to get "myString"?

Corio
  • 395
  • 7
  • 20
  • 2
    No, because *within* the method the identifier `myString` doesn´t even eist. However outside the method you can of course use `nameof(mystring)`. – MakePeaceGreatAgain Aug 09 '17 at 11:51
  • 4
    In the compiled code, `mystring` normally doesn't even exist at the callsite, never mind in the called method. – Jon Hanna Aug 09 '17 at 11:53

1 Answers1

1

You'd have to do

void PrintNameOf(string argument, string name)
{
    Console.WriteLine($"{name} has value: {argument}");
}

string myString = "hello";
PrintNameOf(myString, nameof(myString));
Jakub Dąbek
  • 1,044
  • 1
  • 8
  • 17