1

For some reasons i want to get the name of some variables in my C# Win Forms application. I used the following code

        private void button1_Click(object sender, EventArgs e)
        {
            string my_name = "my_value";
            textBox1.Text = nameof(my_name) + "=" + my_name;
            textBox2.Text = GetNameAndValue(my_name);
        }
        private string GetNameAndValue(string my_parameter)
        {
            return nameof(my_parameter) + "=" + my_parameter;
        }

Textbox1 got the exact result i want

my_name=my_value

However when using the same code in a method i got a different result

my_parameter=my_value

I want to be able to get the result in Textbox1 but using a method

Hadi Fooladi Talari
  • 1,180
  • 1
  • 13
  • 36
EgyEast
  • 1,542
  • 6
  • 28
  • 44
  • 1
    It's very unclear what you're asking. You're correctly getting the name of the parameter, which is `my_parameter`. If you want the information that the value for `my_parameter` was originally from a variable called `my_name`, that information simply isn't part of what the method knows. – Jon Skeet Sep 19 '17 at 17:08
  • How to pass this information (previous parameter_name) through method ? – EgyEast Sep 19 '17 at 17:10
  • 2
    The `nameof()` your method parameter is "my_parameter", if you would like to know the name of "my_name" then you should call `nameof()` and pass _that_ string to your method. – maccettura Sep 19 '17 at 17:10

1 Answers1

1

To get what you want, you'll have to pass the name of the variable to the method as well.

private string GetNameAndValue(string variable_name, string my_parameter)
{
    return variable_name + "=" + my_parameter;
}

And then call it like this:

textBox2.Text = GetNameAndValue(nameof(my_name), my_name);
itsme86
  • 19,266
  • 4
  • 41
  • 57