Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to determine if a method is called by a derived class or directly as itself? C#

Tags:

c#

Is there any direct way to determine if a method in a base class (not an abstract) is called by a derived class or explicitly from somewhere that has created an instance of base class?

like image 751
CJC Avatar asked Dec 30 '25 20:12

CJC


1 Answers

The simplest method is to use reflection:

public virtual void MyBaseClassMethod()
{
    var currType = this.GetType();
    if (currType == typeof(MyBaseClass))
    { 
        // base class instantiated directly.
    }
}
like image 66
pwas Avatar answered Jan 02 '26 10:01

pwas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!