What is sealed class and sealed method in C# with example

Sealed class cannot be inherited and sealed method in C# programming cannot be overridden. If we need to stop a method to be overridden or further extension of a class in inheritance hierarchy,  we need to use Sealed method and Sealed class respectively in C# object oriented programming.

 

Sealed class in C# with example:

A sealed class cannot be inherited. Means, no class can be derived from a sealed class. To make a class sealed, we use the keyword sealed in class declaration. For example, if we seal class A as below source code then class B cannot be derived from it. One question arises immediately that can we create object of sealed class in C# program? Answer is, of course we can create object of sealed class. Purpose of sealed class is only to prevent a class to be inherited.

 

Sealed method in C# :

Prevent overriding a method of a class. This is a method that is declared with the keyword sealed and is always used with combination of override keyword. Derived classes will not be able to override this method as it is sealed for overriding.

Sealed class and sealed method in c sharp

Sealed method example:

In below source code example class B will seal the X(), so, it cannot be overridden / Implemented in class C and class C will use the same X() of class B.

Output:
A::X()
A::Y()

B::X()
B::Y()

B::X()
C::Y()

 

IMPORTANT NOTE:

  • It is not necessary that a sealed class should also contain sealed method. As, sealed class itself means that no class can be derived or extended from it, so, there is no question that a method can be overridden and implemented by derived class. Hence, there is no sense of having sealed method it.
  • Any method can be sealed in the normal class which allow extension, so no derived class can override its own implementation. In very simple word, if I don’t allow a derived class to override it accidentally and write his own definition, I will make it sealed. “Accidentally”, I said because if you can remove the sealed keyword in base class method and override it in your derived class but you will think of the intention of making it sealed and act accordingly in the program. By the way this is the best practice.
  • Sealed class and sealed method in C# programming is used to stop a developer to extend a class or override a method accidentally. If he does so, C# compiler will flash an error. If he really wants to extend or override he can remove the sealed keyword in C# program.

 

Recommended

Read another important C# technical interview question that is Tell me a real-life example of sealed class and method. This is generally asked to experienced professionals. However, if you are a fresher and if the question about sealed class and sealed method is asked then I will recommend you include the use of sealed class and sealed method to your answer. This will give very positive impression to an interviewer.