how to prevent a base class methode from being override by sub class
Asked
Active
Viewed 344 times
3 Answers
10
You don't need to do anything special: methods are non-overridable by default. Rather, if you want the method to be overridable, you have to add the virtual
keyword to its declaration.
Note however that even if a method is non-overridable, a derived class can hide it. More information here: C# keyword usage virtual+override vs. new
-
Yep! but c# compiler allow me to override the methods presents in bases class as default. that is why i confused. – Partha Oct 09 '09 at 10:22
-
1If you are using Visual Studio, type "override" inside the class declaration and intellisense will show you a list of overridable methods. If you try to declare again any method not in this list, you are hiding it, not overriding it. – Konamiman Oct 09 '09 at 10:24
7
If you have a virtual method in a base class (ClassA), which is overriden in an inherited class (ClassB), and you want to prevent that a class that inherits from ClassB overrides this method, then, you have to mark this method as 'sealed' in ClassB.
public class ClassA
{
public virtual void Somemethod() {}
}
public class ClassB : ClassA
{
public sealed override void Somemethod() {}
}
public class ClassC : ClassB
{
// cannot override Somemethod here.
}

Frederik Gheysels
- 56,135
- 11
- 101
- 154
-
That's a good point and probably the source of the problem for Sarathi1904. – Konamiman Oct 09 '09 at 10:26