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