Is is possible to get the name of property that the current class is assigned to in the class it was called from?
Let's say I've got three classes:
class Parent1
{
public Child myName;
public void Foo()
{
myName.Method();
}
}
class Parent2
{
public Child mySecondName;
public void Foo()
{
mySecondName.Method();
}
}
class Child
{
public void Method()
{
Log(__propertyName__);
}
}
I'd like to Log
the value myName
when the Method
is called from Parent1
and mySecondName
if the Method
is called from Parent2
.
Is it possible using reflection and not by passing names by string in argument (I want to use it only for the debugging purposes, I don't want to link those class together in any way)
Using the StackTrace
you can at least get the method and class from which the call was made:
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
Type calledFromType = trace.GetFrame(1).GetMethod().ReflectedType;
This should give you the Parent1
type.
I don't think there is a way to get the name of the variable with which the method was invoked.
You could of course enumerate all fields and properties of calledFromType
and see if one of them is of the Child
type, but you won't get a guarantee that field or property was actually used when invoking.
There is no realistic way to do this using reflection, for a variety of reasons:
There is nothing in the state of your instance that is related to a specific 'owner'.
Your code can be called from anywhere that has access to the property, so a stack trace won't reliably return anything useful.
A reference to your class' instance can be stored in any number of places, including variables and parameters to method calls.
So basically, no. The best you can do is tell it where it is, and even then you fall foul of reference copies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With