Preventing a static method in base class from being called through derived class?

Kamran Ahmed Khan
2 min readJan 26, 2023

--

It is not possible to prevent a static method in a base class from being called through a derived class, as static methods are not overridden in derived classes. They are inherited by the derived class and can be called using the derived class name. However, if you want to prevent the static method from being called, you could make it private or protected in the base class, which would prevent it from being called outside the base class or derived classes. Additionally, you could also add additional logic within the static method to check the type of the calling object and prevent it from being called if it is an instance of a derived class.

Here is an example of making a static method private in a base class to prevent it from being called through a derived class:

class BaseClass {
private static void MyStaticMethod() {
// Method logic here
}
}

class DerivedClass : BaseClass {
// This class cannot access the private MyStaticMethod
}

And here is an example of adding additional logic to a static method to prevent it from being called if it is an instance of a derived class:

class BaseClass {
public static void MyStaticMethod() {
if (this is DerivedClass) {
throw new Exception("MyStaticMethod cannot be called on an instance of DerivedClass");
}
// Method logic here
}
}

class DerivedClass : BaseClass {
// This class can access the MyStaticMethod but it will throw an exception
}

Please note that this second example will not work as you cannot use this keyword in static methods, because they are not bound to an instance of the class.

--

--