Petar Ivanov
Petar Ivanov

Reputation: 93030

Can you use reflection to find out the type of the object on which the current method is executing?

I know how to get the current method (MethodBase.GetCurrentMethod()).

However, the DeclaringType property of MethodBase will give me the type on which the method is defined.

I am interested in the type of the method on which it was actually called at runtime.

Upvotes: 2

Views: 93

Answers (1)

JaredPar
JaredPar

Reputation: 754763

If you mean the type of the object itself then just use this.GetType()? That will give you the type of this on which the current method is executing.

If you mean the type of the reference on which the method was executed then that's not really possible to determine. Consider virtual methods as an example.

abstract class Animal {
  public abstract void MakeNoise();
}
abstract class Dog : Animal { }
class Labrador : Dog {
  public override void MakeNoise() {
    ...
  }
}

The reference type could be Animal but if the object is Labrador then that version of the MakeNoise method will be invoked. Their is no way from the MakeNoise method to know if it' was invoked from an Animal, Dog or Labrador instance.

Upvotes: 6

Related Questions