Let me use the following example to explain my question:
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World"';
string Hello = ExampleFunction(WhatIsMyName);
When I pass the variable "WhatIsMyName" to the example function, I want to be able to get a string of the original variables name. Perhaps something like:
Variable.OriginalName.ToString()
Is there any way to do this?
No, but whenever you find yourself doing extremely complex things like this, you might want to re-think your solution. Remember that code should be easier to read than it was to write.
You could use reflection to get all the properties of an object, than loop through it, and get the value of the property where the name (of the property) matches the passed in parameter.
Do this
or naming in code by hand
using this class
Code tested and most elegant I can come up with.
I know this is an old question but in C# 6.0 they Introduce the nameof Operator which should solve this issue. The name of operator resolves the name of the variable passed into it.
Usage for your case would look like this:
A major benefit is that it is done at compile time,
More information can be found here
Older Version Of C 3.0 and above
To Build on Nawfals answer
Three ways:
1) Something without reflection at all:
2) Uses reflection, but this is way faster than other two.
3) The slowest of all, don't use.
To get a combo parameter name and value, you can extend these methods. Of course its easy to get value if you pass the parameter separately as another argument, but that's inelegant. Instead:
1)
2)
3)
1 and 2 are of comparable speed now, 3 is again sluggish.
The short answer is no ... unless you are really really motivated.
The only way to do this would be via reflection and stack walking. You would have to get a stack frame, work out whereabouts in the calling function you where invoked from and then using the CodeDOM try to find the right part of the tree to see what the expression was.
For example, what if the invocation was ExampleFunction("a" + "b")?