tags:

views:

107

answers:

2
+1  Q: 

OOPs clarification

how to prevent a base class methode from being override by sub class

+6  A: 

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: http://stackoverflow.com/questions/159978/c-keyword-usage-virtualoverride-vs-new

Konamiman
Yep! but c# compiler allow me to override the methods presents in bases class as default. that is why i confused.
Sarathi1904
If 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
+5  A: 

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
That's a good point and probably the source of the problem for Sarathi1904.
Konamiman