Can you allow class to be inherited, but prevent the method from being over-ridden

Can you allow class to be inherited, but prevent the method from being over-ridden
LVL 1
chuang4630Asked:
Who is Participating?
 
Carl TawnSystems and Integration DeveloperCommented:
As long as the method is not virtual, or itself an override, then it cannot be overridden by a derived class. It can, however, be hidden by the derived class.
0
 
shy_talkCommented:
Yes, you prevent inheritance, either by not using the "virtual" keyword when you declare the method in the base class, or by using the "sealed" keyword if you are inheriting a method [that is already virtual in the base class]. Drop this code into a new console app to illustrate. Should be OK.

   class BaseClass
   {
      // Overrideable
      protected virtual void VirtualMethod() { }
      protected virtual void VirtualMethodThatWillBeSealed() { }
     
      protected void NonVirtualMethod() { }
   }
   
   class Subclass : BaseClass
   {
      // Overrides OK
      protected override void VirtualMethod() { }

      // Can override and seal the other virtual method
      protected sealed override void VirtualMethodThatWillBeSealed() { }
     
      // Cannot override the non-virtual method!!!      
      protected override void NonVirtualMethod() { }
   }
   
   
   class SubSubclass : Subclass
   {
      // Virtual method that was not sealed still overrides OK
      protected override void VirtualMethod(){}

      // But this method was sealed, do does not compile!!!
      protected override void VirtualMethodThatWillBeSealed() { }  
   }
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.