2

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

Konamiman
  • 49,681
  • 17
  • 108
  • 138
Partha
  • 2,062
  • 6
  • 24
  • 31

3 Answers3

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

Community
  • 1
  • 1
Konamiman
  • 49,681
  • 17
  • 108
  • 138
  • 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
  • 1
    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 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
-1

You can also use ABSTRACT for Parent Class . As a result you cant override by sub class

abstract main{
}

class sub extent main{
}
Mat
  • 202,337
  • 40
  • 393
  • 406
George
  • 11
  • 1