What are sealed classes in c#?
A class that any other class cannot inherit is a sealed class in c#. The primary purpose of these types of classes is to provide security to the program. Furthermore, the functionality of sealed classes cannot be extended via inheritance.
We need sealed classes when we want to break our program into modules and classes that do not need to interact with each other and only cater to specific operations.
Syntax
The following is how a sealed class is defined in c#:
sealed class <classname>{//data members//constructors//getters,setters//other methods}
The sealed keyword in c# is used to determine a sealed class. Like a regular class, it has
Example
Let's see the following example to see how sealed classes work:
using System;class Example{//sealed classsealed class Multiply{public Multiply(){}public int mul(int x, int y){return x * y;}}static void Main(){//object of sealed class MultiplyMultiply res = new Multiply();int prod = res.mul(5, 3);Console.WriteLine(prod);}}
The code snippet above represents a Multiply sealed class with a function called mul and a default constructor Multiply() that does nothing. We pass two integers to the method of the sealed class, and it returns us the result.
Let's try to inherit this sealed class:
using System;class Example{sealed class Multiply{public Multiply(){}public int mul(int x, int y){return x * y;}}//inheriting a sealed classpublic class Lcm : Multiply{}static void Main(){Multiply res = new Multiply();int prod = res.mul(5, 3);Console.WriteLine(prod);}}
As seen above, an error is thrown indicating that the derived class cannot inherit the sealed class. However, the same does not happen if the sealed class inherits some other non-sealed class:
using System;class Example{public class Add {public Add(){}public int addNums(int x, int y){return x + y;}}//inheritance of other classes in sealed classsealed class Multiply : Add{public Multiply(){}public int mul(int x, int y){return x * y;}}static void Main(){Multiply res = new Multiply();//function call to the method of the base classint sum = res.addNums(5, 3);Console.WriteLine(sum);}}
So, it can be seen that inheritance can follow a hierarchy until a sealed class, after which inheritance cannot occur.
Uses
There are specific scenarios where we need to work with sealed classes:
When no overloading/overwriting is required in the code.
Security is a priority. It provides the abstraction of code.
Separation of independent modules/classes is required. It gives developers control over coupling.
Conclusion
Sealed classes support in C# allows inheritance up to a specific class after which inheritance cannot occur. This feature is helpful if we want to limit a specific class's scope and its methods. Security and the separation of different modules also take advantage of this feature.
Free Resources