It's complicated here. Is it possible, using any method, to implicitly determine the name of the property that is passed as a parameter to the method?
(This may seem like a duplicate of another question at first glance, but there are subtle but important differences, since we always work with properties that are key).
Here is an example script:
public class Foo { public string Bar { get; set; } } public void SomeStrangeMethod() { Foo foo = new Foo() { Bar = "Hello" }; string result = FindContext(foo.Bar);
Assume that inside the FindContext the passed parameter will always be a property of the object. Catch, we do not know which object.
Obviously, the problem can be easily solved by passing a second parameter that provides the missing context, i.e. ...
FindContext(foo, foo.Bar); FindContext("Bar", foo.Bar);
.... but this is not what I want. I want to be able to pass one parameter and determine the property name represented by the value.
I understand that when passing a parameter, the method context for FindContext does not contain enough information to determine this. However, using some sleight of hand around the stack and IL traces, perhaps we can still do this. The reason I think this should be possible:
The requirement is that the parameter passed to FindContext must always be a property of another object, and we know that using reflection we can get the specified property names.
Using StackTrace, we can get the call context.
From the context of the call, we must somehow find the character used.
From this symbol, we must either get the name of the property or the type of the caller, which through (1) should be able to convert to the property of the caller.
Does anyone know how to do this? Note. This question is complex, but I do not think this is impossible. I will not accept any "impossible" answers if someone cannot demonstrate why this is not possible.