Search code examples
c#nameof

How to get the name of string parameter in C# Win Forms application using a method?


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


Solution

  • 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);