755
755

Reputation: 3091

Automatically call superclass method in constructor

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)"

Upvotes: 3

Views: 1375

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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) {
    }
}

Upvotes: 5

Related Questions