How to Seal a Class in C#

Programmers, in some instances, do not want to let the future generations of programmers extend their classes and, fortunately, C# provides a useful feature to help prevent classes from inheriting known as sealing. In C#, the objective of making a class sealed is to indicate that the class is a special class that prevents it from being extended to provide any additional functionality to other classes through inheritance. Not only can developers seal a class, but they can also prevent the overriding of methods and properties as well.

Want to learn C# in a classroom setting, while still being in the comfort of your own home? Check out our list of the Best Online Courses to Learn C#.

The C# seal Keyword

In C#, programmers can seal a class by using the sealed keyword. You can define a sealed class in different ways as depicted in the following code example:

sealed class MyClass
{
   public string Name;
   public string City;
   public int Age;
}

sealed public class MyClassTwo
{
  // Class Implementation
}

What are Sealed Classes in C#?

As you already know, the sealed keyword is used to lock a class, so be sure that the class you are going to make sealed is not the base class for any other class. The following code example shows how you can define a sealed class in C#:

    sealed class Student
    {
       public string Name = "George Clayton";
       public void GetBasicInfo()
       {
          Console.WriteLine("Name: {0}", Name);
       }
    }
    
    public class StudentDetails : Student
    {
       public int Age = 22;
       public string City = "New York";
       
       public void GetDetails()
       {
          Console.WriteLine("Age: {0}", Age);
          Console.WriteLine("City: {0}", City);
       }
    }

    class Program
    {
       static void Main(string[] args)
       {
          StudentDetails obj = new StudentDetails();
          obj.GetDetails();  // OK
          obj.GetBasicInfo();  // Error
          Console.ReadLine();
       }
    }
}

In the above C# code example, we defined the Student
class as sealed. We are also trying to inherit the properties of the Student class into the StudentDetails class. But, if you try to compile the above code, you would get the following error:

C# Seal Classes Error

The error occurs at compile-time and states that the properties of the sealed class Student cannot be inherited into another class StudentDetails. Remember, this occurs because we cannot inherit from a sealed class, which is part of the reason we seal a class to begin with.

So far we have seen how we can use sealed classes to prevent inheritance in C#. In the next section, we will learn how to prevent methods from inheriting by using the sealed keyword with the method name.

Read: Working with Static Classes and Static Methods in C#

How to Seal a Method in C#

In C#, programmers can use the sealed keyword on methods too. Developers can seal a method in situations where they do not want an overridden method to be further overridden by another class. Let’s take the following code example for illustration:

  class Electronics {
    public virtual void Test() {
    Console.WriteLine("Test Method in Electronics Class");
    }
  }

  class Television : Electronics {

    // sealed method
    sealed public override void Test() {
      Console.WriteLine("Test Method in Television Class");
    }
  }

  class LCD : Television {
    public override void Test() {  // trying to override sealed method
      Console.WriteLine("Test Method in LCD Class");
    }
  }   

In the above C# code, we have overridden the Test() method inside the Television class, as you can see in the following code snippet from our example:

  class Television : Electronics 
  {
    sealed public override void Test()  // sealed method
    {     
      Console.WriteLine("Test Method in Television Class");
    }
 }

So far so good. However, we do not want this method to be further overridden in the derived class so we have used the sealed keyword before the Test() method in the Television class. And, if we try to further override this sealed method in the LCD class, the compiler will raise an error, as shown in the following snapshot:

C# Seal keyword tutorial

What are the Features of Sealed keyword in C#?

There are certain features of the sealed keyword in C# worth mentioning, which include:

  • When we seal a class in C# we can easily unseal it in the future without any concern of breaking any compatibility issues.
  • Sealing a class provides security and a sealed class saves itself from data corruption and invalid use. When you unseal a class, it enhances the chances that the derived class can misuse or manipulate the data of the base (unsealed) class.
  • There are a few things you cannot inherit. You can neither inherit the structs as they are sealed implicitly nor you can seal the local variables.

Final Thoughts on Sealed Classes in C#

Sealing classes allows the programmers to lock the class and thus prevents data misuse. It also helps the programmers in achieving security. For example, if you have a class that implements system security features, you might not want anyone to extend it because doing so can create a security back door to the system.

Read more C# programming tutorials and software development guides.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read