Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically call superclass method in constructor

Tags:

c#

.net

Is there a way in C# to guarantee that a method of a superclass will be automatically called by every subclass constructor?

Specifically, I am looking for a solution that only adds code to the superclass, so not "base(arguments)"

like image 497
755 Avatar asked Jul 15 '26 06:07

755


1 Answers

The only way to guarantee it is to make the call in the constructor of the base class. Since all subclasses must call a constructor of the base, your method of interest will be called as well:

class BaseClass {
    public void MethodOfInterest() {
    }
    // By declaring a constructor explicitly, the default "0 argument"
    // constructor is not automatically created for this type.
    public BaseClass(string p) {
        MethodOfInterest();
    }
}

class DerivedClass : BaseClass {
    // MethodOfInterest will be called as part
    // of calling the DerivedClass constructor
    public DerivedCLass(string p) : base(p) {
    }
}
like image 78
Sergey Kalinichenko Avatar answered Jul 19 '26 19:07

Sergey Kalinichenko



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!