What is sealed class in C#?
A sealed class in C# programming language is not inherited by any of the other classes. When a class is declared as sealed, it signifies that it has been finalized and can no longer be changed.
Syntax
In C#, the syntax for declaring a sealed class is as shown below:
{
//class members and method
}
Now, let’s see an example of a sealed class in C# programming.
Example: Simple Program of Sealed Class in C#
In this example program, we create a sealed class name as Sealed_Class, which includes a function called Message() that just prints a message to the console. To display the message, we create a new instance of the SealedClass and invoke its Message function in the Main method.
sealed class Sealed_Class
{
public void Message()
{
Console.WriteLine("This is an example program of sealed class in C#");
}
}
class MyProgram
{
static void Main()
{
Sealed_Class obj = new Sealed_Class();
obj.Message();
}
}
In the above, the class named Sealed_Class is a sealed class that we can’t derive from, so it can’t be inherited by another class. The output of the above-implemented code is shown below:
Note: Sealing a class is important when you wish to ensure that a class’s functionality remains consistent throughout the program. As other classes continue to inherit from a sealed class. Furthermore, sealed classes can be generated and used in the same way as any other class. The sole distinction is that these cannot be inherited.
Conclusion
A sealed class in C# cannot be modified or inherited. It prevents another change or extension of the class, which is essential when you wish to ensure that a class’s behavior and functionality remain consistent throughout the program. In the above writing, you have simply seen an example of a sealed class that is used in the C# program.