Sealed Keyword in C#

The “sealed” keyword in C# is used to apply limitations to classes, methods, properties, indexes or events. Now, what kind of limitations you may ask? Well, let’s find out.

Purpose of ‘Sealed

This concept of sealing is many a time used to encapsulate the logic that needs to be reused throughout the application without any changes made to it. The ‘sealed’ keyword is used before or after the access modifier to define a sealed class. When the compiler reads the keyword ‘sealed’, it knows that this class cannot be extended.

When a sealed class is created, this class cannot be derived. If any class tried to inherit from a sealed class, an error message is generated by the compiler. In the inheritance hierarchy, a sealed class is the last level class. Classes which do not have any inheritance relationship with other classes can also be marked as sealed. Sealed classes can define constructors.

Sealed Class Syntax

 sealed class ABC { }
 class XYZ : ABC { } //Invalid

Below is the error message generated on the above code

When to use Sealed Classes

The best use of sealed class happens when the mentioned class has static members. Best example of this that is often given is ‘Pens’ and ‘Brushes’ classes of the System.Drawing namespace. The Pens class represents the pens for the standard colors. This class only contains static members. For instance, ‘Pens.Blue’ represents a pen with blue color. Same way, the ‘Brushes’ class represents standard brushes such as ‘Brushes.Blue’ or ‘Brushes.Red’ which represent brushes of blue and red color respectively. System.String is an example of inbuilt sealed class. This class can be instantiated but you cannot inherit it.

Sealed Class Features

There are some things one needs to keep in mind before making use of sealed class. Make sure that local variables, interfaces and constructors cannot be sealed but a constructor can be defined by a sealed class. Another thing to keep in mind is that a sealed class can neither be abstract nor static (static classes are sealed implicitly). Also, virtual and abstract methods cannot be defined in a sealed class. Most importantly, a sealed class should never be a base class. Lastly, Struct, Enum and value types are all sealed implicitly and hence cannot be inherited.

Example of Sealed Class

    public sealed class SealedExampleClass
        public int sum(int a1, int a2)
            return a1 + a2;

    static void Main(string[] args)
        // Creating an object of SealedExampleClass
        SealedExampleClass sec = new SealedExampleClass();

        // executing the function
        int totalsum = sec.sum(6, 4);
        Console.WriteLine("Total Sum = " + totalsum.ToString());

A class is made ‘Sealed’ by adding the keyword sealed before ‘class’ keyword and after the access modifier of the class.

Why to use a Sealed Class?

  1. Using sealed class helps in protection of the code as it prevents any sort of corruption in code by restricting unnecessary inheritance from a class
  2. A sealed class can never be used as a base class. Also, sometimes code optimizations lead to sealed classes being called faster.
  3. A sealed class helps maintain the quality, regularity and consistency of the code.

Sealed Method

When a method is defined as sealed, it cannot override the properties of a parents (base) class. Technically speaking, every method is essentially a sealed method as overriding is not possible i.e. no child class can override that method unless the method is declared as ‘virtual’ in the parent class.   

Similar to the sealed class, there are some things to keep in mind before using sealed methods. In a sealed method, the keyword ‘sealed’ must always be partnered with the keyword ‘override’. A sealed method cannot be defined in the base class but one can override the virtual methods from the base class as sealed. When a sealed method is defined in the derived class, the abstract methods can also override them as sealed since they are implicitly virtual. Another strong point to note is an interface can also define a sealed method but in a derived interface, a virtual method cannot be overridden as sealed.

Sealed Method Syntax with Example

Let us consider below class hierarchy

    class ABC
 	public virtual void func() {}

    class DEF: ABC 
        public sealed override void func() {}

    class XYZ: DEF
        public override void func() {} //Invalid

When the virtual methods from the parent class are overridden by the child class, the sealed modifier is used by the child class in the method so that further overriding of the method should not occur.

In the code above, ‘XYZ.func()’ cannot override inherited member ‘DEF.func()’ because it is sealed.

Real Time Use of Sealed Method in C#

At times we might implement functionalities that might consume our resources and must be limited to our classes only. For example if we have defined a class that sends SMS or Email Messages and we might not need other classes to inherit our classes but me need to keep these classes public so that other users can use our classes to implement these functionalities. In such scenarios, we might seal the classes.

Let us look at the following example of a sealed method in a derived class:

    public class Notification
      public virtual void processing() 
      { Console.WriteLine("Notification processing"); }  
      public virtual void send()
      { Console.WriteLine("Notification sent"); }  
    public class SMSNotification: Notification  
       public override void processing() 
       { Console.WriteLine("Notification processing via SMS"); }  
       public sealed override void send() {   
       Console.WriteLine("Notification sent via SMS");   
    public class EmailNotification : SMSNotification  
       public override void processing() 
          Console.WriteLine("Notify 'SMS’ processed via Email"); 

       public override void send() 
       { Console.WriteLine("Notify that ‘SMS sent’ via Email"); }  

    public class SealedExample  
       public static void Main()  
           Notification n = new Notification();  
           SMSNotification cn = new SMSNotification();  
           EmailNotification en = new EmailNotification();  

Output would be as follows:


So, when you plan to design your class library and wish to restrict your classes from being inherited by other users, you can use sealed keyword in your classes and methods.

Leave a Comment

Your email address will not be published.