The C# sealed keyword imposes limitations on both classes and methods. When a class is marked as sealed, it becomes non-inheritable. Similarly, when a method is sealed, it becomes non-overridable. This keyword is frequently used to restrict the extension of classes undesirably and to guarantee that specific methods remain unaltered in subclasses.
Note: Structs are implicitly sealed, therefore they can't be inherited.
C# Sealed class
In C# programming, a sealed class is one that cannot be extended by any other class. By using the sealed keyword to create a sealed class, we can essentially restrict further inheritance, preventing the creation of subclasses.
The sealed class proves beneficial in scenarios where there is certainty that no other class will require altering the behavior of the sealed class or when optimizing performance by removing the need for runtime inheritance checks.
Syntax:
It has the following syntax:
sealed class ClassName
{
// data members
// methods
}
In this particular syntax,
- ClassName signifies the identifier for the class.
C# Sealed Class Example without using sealed class
Let's consider an example to demonstrate the restricted class concept in C# without explicitly using the "sealed" keyword.
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:
Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'
Explanation:
In this instance, we will endeavor to define a sealed class named Creature containing a function consume. However, as sealed classes are not inheritable, attempting Dog: Creature will lead to a compilation error. Absence of the sealed modifier would enable Dog to inherit both consume and its bark function, invoked by Main.
C# Sealed Example using Sealed Class
Let's consider a scenario to demonstrate the sealed class in C#.
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:
Car started with a key.
Explanation:
In this illustration, we define a fundamental class named Vehicle, containing a virtual Start function. Additionally, there is a derived class named Car, which is marked as sealed and provides an implementation for the virtual method. Within the Main function, an instance of Car calls its Start method, displaying the message "Car started with a key." Since the Car class is sealed, it is not permissible for any other class to derive 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 C# programming, a sealed method within a class prevents it from being overridden in any derived classes. This feature is typically used in combination with the override keyword. To seal a method, it must first override a method from the base class; the sealed keyword cannot be used otherwise.
Syntax:
It has the following syntax:
sealed override access_modifier return_type MethodName(parameters)
{
// method body
}
The sealed keyword in C# prevents further overriding of a method and requires the override keyword to be used in a method.
C# Sealed Example using the sealed Keyword with Methods to Prevent Overriding
Let's examine an example to demonstrate the sealed keyword in C#.
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:
Compile Time Error: 'BabyDog.run()': cannot override inherited member 'Dog.run()' because it is sealed
Explanation:
In this instance, the compilation will fail because the run method in the Dog class is marked as sealed, preventing any overriding by the BabyDog class. If the run method override in the BabyDog class is enabled, it will simply inherit the run method from the Dog class, resulting in the 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's consider a scenario to demonstrate the improper application of the "sealed" keyword with local variables in C#.
Example
using System;
public class TestSealed
{
public static void Main()
{
sealed int x = 10;
x++;
Console.WriteLine(x);
}
}
Output:
Compile Time Error: Invalid expression term 'sealed'
Explanation:
In this instance, the code will fail to compile because C# does not allow the use of the sealed keyword with local variables like int x. The sealed modifier is specifically designed for classes or method overrides, and cannot be used with primitive data types.
C# Sealed example to Sealing an Overridden Method to Restrict Further Overriding
Let's consider an instance to demonstrate how to finalize an overridden method to prevent additional overriding in C#.
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:
Manager is managing the team
Project Manager is planning tasks
Explanation:
In this illustration, we establish an Employee class containing a virtual Work function, which is then overridden in a sealed Manager class to restrict further alterations. Additionally, we introduce a Plan function within the ProjectManager class. Within the Main function, a ProjectManager object calls the Work method (inherited from Manager) and the Plan method.
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 summary, in C#, the sealed keyword is employed to restrict inheritance by prohibiting other classes from deriving from a sealed class or inhibiting additional overriding of a sealed method. This practice aids in safeguarding the consistency of a class's structure, thus preventing any alterations to its implementation. Furthermore, it can lead to performance enhancements as the runtime is aware that the type is not extendable.
A sealed class is considered final and cannot be extended, while a sealed method is a method that can be overridden in a derived class but cannot be further overridden in subsequent subclasses.
C# Sealed FAQs
1) What is the sealed keyword in C#?
In C# programming, the sealed keyword is employed to block inheritance of a class or overriding of a method. It is applicable to classes, methods, and properties.
2) Can a sealed class be instantiated in C#?
In C#, sealed classes are instantiated in the same way as regular classes, but they are restricted from being used as a base class for another class.
3) Can members of a sealed class be overridden?
If a method is marked as virtual in the parent class, a subclass can replace it following the standard procedure. However, if the subclass seals that method, any subsequent subclasses will be unable to override it.
4) Is it possible to seal a method in C#?
Yes, a method can be marked as sealed, but this can only be done if it is overriding a virtual method. Sealing an overridden method prevents any further overriding in classes that inherit from it.
5) Is sealed connected with static in C#?
No, there is a distinction between a static class and a sealed class. While a static class is inherently sealed, a sealed class is not necessarily static.