In c#, sealed is a keyword used to stop inheriting the particular class from other classes. We can also prevent overriding particular properties or methods based on our requirements.
Generally, when we create a particular class we can inherit all the properties and methods in any class. If you want to restrict access to a defined class and its members, then by using a sealed keyword, we can prevent other classes from inheriting the defined class.
In c#, a sealed class can define by using a sealed keyword. As discussed, when we define a class with the sealed keyword, then we don’t have a chance to inherit that particular class.
The following are the various ways of defining sealed classes in the c# programming language.
If you observe the above code snippet, we defined various classes with a sealed keyword to ensure that the defined classes are not inheritable to any class. In c#, we can use a sealed keyword before or after the access modifier to define sealed classes.
Following is the example of using a sealed keyword to define sealed classes in the c# programming language.
If you observe the above example, we defined a class “Users” with a sealed keyword, and we are trying to inherit the properties from the Users class using the Details class.
When you execute the above c# program, we will get the result below.
If you observe the above result, we are getting compile-time errors because we tried to inherit sealed class properties in another class.
In c#, we can also use the sealed keyword on a method or property that overrides a virtual method or property in a base class to allow other classes to derive from the base class and prevent them from overriding specific virtual methods or properties.
Following is the example of using a sealed keyword on a method that overrides a virtual method in a base class.
If you observe the above example, we used a sealed keyword on the method (GetInfo) that overrides a base class virtual method. In the above example, class C is inherited from class B, but class C cannot override a virtual method GetInfo that is declared in class A because that method is sealed in class C.
When you execute the above c# program, you will get a result, as shown below.
This is how you can use the sealed keyword on a method or property that overrides a base class virtual method or property.
Instead of using sealed keyword, we can prevent derived classes to override base class methods or properties by not declaring them as virtual.
The following are the important points that we need to remember about the sealed keyword in the c# programming language.