C# Sealed

The C# sealed keyword applies restrictions on the class and method. If we create a sealed class, it cannot be inherited. If we create a sealed method, it cannot be overridden. It is commonly utilized to prevent unwanted extension of classes and to ensure that certain methods are not modified in the derived classes.

Note: Structs are implicitly sealed, therefore they can't be inherited.

C# Sealed class

In the C# programming language, a sealed class is a class that cannot be inherited from by any other class. When we make a sealed class with the sealed keyword, we can effectively lock the class, and no one can inherit new classes from it.

The sealed class is helpful when we know that no other class will ever need to change the behavior of the sealed class, or if we need to optimize performance by eliminating the overhead of runtime checking for inheritance.

Syntax:

It has the following syntax:

Example

sealed class ClassName

{

    // data members

    // methods

}

In this syntax,

  • ClassName: It represents the name of the class.
  • C# Sealed Class Example without using sealed class

Let us take an example to illustrate the sealed class without using sealed in C#.

Example

Example

using System;  

sealed public class Animal{  

    public void eat() { Console.WriteLine("eating..."); }  

}  

public class Dog: Animal  

{  

    public void bark() { Console.WriteLine("barking..."); }  

}  

public class TestSealed  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.eat();  

        d.bark();    

    }  

}

Output:

Output

Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'

Explanation:

In this example, we will attempt to declare a sealed class Animal with a method eat, but since sealed classes can't be inherited, Dog: Animal will result in a compiler error. Without the sealed keyword, it would allow Dog to inherit eat as well as its bark method, called by Main.

C# Sealed Example using Sealed Class

Let us take an example to illustrate the sealed class in C#.

Example

Example

using System;

public class Vehicle

{

    public virtual void Start()

    {

        Console.WriteLine("Vehicle started.");

    }

}

public sealed class Car : Vehicle

{

    public override void Start()

    {

        Console.WriteLine("Car started with a key.");

    }

}

class Program

{

    static void Main()

    {

        Car myCar = new Car();

        myCar.Start();

    }

}

Output:

Output

Car started with a key.

Explanation:

In this example, we declare a base class, Vehicle, with a virtual Start method and a sealed class, Car, that overrides the virtual method. In Main , a Car object invokes its Start method, outputting "Car started with a key." As the Car is sealed, no class may inherit from it.

When to Use Sealed Classes?

We can use sealed classes in different contexts. Some of them are as follows:

  • It is used to avoid unwanted inheritance.
  • It is used to protect delicate behavior against being overridden.
  • It is used to maximize performance in some cases.
  • C# Sealed method

In the C# programming language, a sealed method cannot be overridden in derived classes. It is used in conjunction with the override keyword. A method can only be sealed if it overrides a base class method. The sealed keyword cannot be applied to a method unless it has been overridden.

Syntax:

It has the following syntax:

Example

sealed override access_modifier return_type MethodName(parameters)

{

    // method body

}

The sealed method in C# cannot be overridden further. It must be used with the override keyword in a method.

C# Sealed Example using the sealed Keyword with Methods to Prevent Overriding

Let's see an example to illustrate the sealed method in C#.

Example

Example

using System;  

public class Animal{  

    public virtual void eat() 

{ 

Console.WriteLine("eating..."); 

}  

    public virtual void run() 

{ 

Console.WriteLine("running..."); 

}  

  

}  

public class Dog: Animal  

{  

    public override void eat() 

{ 

Console.WriteLine("eating bread..."); 

}  

    public sealed override void run() {   

    Console.WriteLine("running very fast...");   

    }  

}  

public class BabyDog : Dog  

{  

    public override void eat() 

{ 

Console.WriteLine("eating biscuits..."); 

}  

    public override void run() 

{

 Console.WriteLine("running slowly..."); 

}  

}  

public class TestSealed  

{  

    public static void Main()  

    {  

        BabyDog d = new BabyDog();  

        d.eat();  

        d.run();  

    }  

}

Output:

Output

Compile Time Error: 'BabyDog.run()': cannot override inherited member 'Dog.run()' because it is sealed

Explanation:

In this example, we will not compile because Dog has sealed the run method and BabyDog cannot override it. If the run override in BabyDog is uncommented out, it would inherit Dog's run method and output "eating biscuits..." followed by "running very fast...".

Note: Local variables can't be sealed.

Invalid Use of sealed with Local Variables in C#

Let us take an example to illustrate the invalid use of sealed with local variables in C#.

Example

Example

using System;  

public class TestSealed  

{  

    public static void Main()  

    {  

        sealed int x = 10;  

        x++;  

        Console.WriteLine(x);  

    }  

}

Output:

Output

Compile Time Error: Invalid expression term 'sealed'

Explanation:

In this example, we will not compile since C# does not support using the sealed keyword with local variables such as int x. sealed is only applicable to classes or method overrides, but not to primitive variables.

C# Sealed example to Sealing an Overridden Method to Restrict Further Overriding

Let us take an example to illustrate how to seal an overridden method to restrict further overriding in C#.

Example

Example

using System;

public class Employee

{

    public virtual void Work()

    {

        Console.WriteLine("Employee is working");

    }

}

public class Manager : Employee

{

    public sealed override void Work()

    {

        Console.WriteLine("Manager is managing the team");

    }

}



public class ProjectManager : Manager

{

    public void Plan()

    {

        Console.WriteLine("Project Manager is planning tasks");

    }

    // Cannot override Work() here because it is sealed in Manager

}



class Program

{

    static void Main()

    {

        ProjectManager pm = new ProjectManager();

        pm.Work(); 

        pm.Plan(); 

    }

}

Output:

Output

Manager is managing the team

Project Manager is planning tasks

Explanation:

In this example, we define an Employee class with a virtual Work method, override it in a sealed Manager class to prevent further modifications, and introduce a Plan method in the ProjectManager class. In the Main function, a ProjectManager instance invokes Work(from Manager) and Plan.

Features of Sealed in C#

There are several features of Sealed in C#. Some of them are as follows:

  • Sealed classes cannot be inherited.
  • Sealed method cannot be overridden, but it can be declared inside a class that is inheritable.
  • All classes are inheritable unless marked as sealed in C#.
  • Structures are implicitly sealed, so we cannot inherit from them.
  • Sealed helps to enhance the performance because sealed methods are faster due to compiler optimizations.
  • Conclusion

In conclusion, C# sealed is used to limit inheritance by disallowing other classes from inheriting from a sealed class or preventing further overriding of a sealed method. It helps to preserve the integrity of a class's design, which prevents its implementation from being modified. It can also provide performance benefits because the runtime knows that the type cannot be extended.

A sealed class is final and cannot be abstracted, whereas a sealed method is a method that is overridden in a derived class but cannot be overridden again in subsequent subclasses.

C# Sealed FAQs

1) What is the sealed keyword in C#?

In the C# programming language, the sealed keyword is used to prevent a class from being inherited or a method from being overridden. It can be used on classes, methods, and properties.

2) Can a sealed class be instantiated in C#?

In C#, sealed classes can be instantiated like regular classes; however, they cannot act as a base for another class.

3) Can members of a sealed class be overridden?

If a method is declared virtual in the base class, a derived class may override it in the normal way. If the derived class seals that method, further subclasses cannot override it.

4) Is it possible to seal a method in C#?

Yes, a method can be sealed, but only if it is an override of a virtual method. Sealing an overridden method that prevents further overriding in derived classes.

5) Is sealed connected with static in C#?

No, a static class and a sealed class are different. A static class is automatically sealed, but a sealed class does not have to be static.

Input Required

This code uses input(). Please provide values below: