In C# if we inherit from a class, it allows us to override the virtual methods.
This can be prevented by not using the virtual keyword with a method but still it can be hidden by implementing the method with the new keyword.
Is there anyway to prevent overriding and shadowing without making it the method private?
class myBaseClass{
public void method1(){ //Implementation }
}
class myDerivedClass : myBaseClass{
public new void method1() { //new Implementation }
}
It can always be hidden, but that’s not overriding – it’s shadowing. It’s important to understand the difference between the two. You can’t prevent shadowing though (while permitting the class itself to be derived from), no. Why do you want to? What ill effect are you trying to prevent?
Sealing the class itself is a separate option though:
Personally I like to seal any class which I don’t design to be derived from, but that’s a different (and controversial) matter.