Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get own property name from parent class using reflection

Tags:

c#

reflection

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)

like image 380
Adassko Avatar asked Feb 16 '23 04:02

Adassko


2 Answers

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.

like image 84
C.Evenhuis Avatar answered Feb 17 '23 19:02

C.Evenhuis


There is no realistic way to do this using reflection, for a variety of reasons:

  1. There is nothing in the state of your instance that is related to a specific 'owner'.

  2. Your code can be called from anywhere that has access to the property, so a stack trace won't reliably return anything useful.

  3. 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.

like image 22
Corey Avatar answered Feb 17 '23 20:02

Corey