Sealed Keyword in C#

 

Sealed keyword is used to restrict the class from inheriting. A class that is declared using sealed keyword is called as sealed class. A sealed class cannot be inherited by any other class i.e., sealed classes doesn't support inheritance.

 

Eg:

 

sealed class Company 

{ 

       ............. 

       ............. 

} 

because Company class is sealed we cannot inherit that class. 

//the below code will give errors

class Employee : Company 

 

        ....... 

} 

The above code will give the errors because it is trying to inherit sealed class Company. Even if a sealed class cannot be inherited we can still consume it by creating its object. For example String is a sealed class which cannot be inherited but can be consumed anywhere by creating its object. 

Sealed method: A method which cannot be overriden under a child class is known as a seald method. By default every method is a seald method because overriding of a method is not possible until it is declared as virtual under a class. 

class Class1 

{ 

        public virtual void Show() 

        {

 

        } 

}

 

class Class2 : Class1 

{ 

       public override void Show() 

       { 

 

       } 

} 

 

class Class3 : Class2 

{ 

        public override void Show() 

        {

 

        } 

}

In the above case even if Class2 didn't override the method then also Class3 can override the method. 

A child class if requires can restrict further overriding of its parent classes's virtual method by using Seald modifier on the method while overriding. So that its child class cannot override the method. 

class Class1 

{ 

        public virtual void Show() 

       

 

        } 

}

  

class Class2 : Class1 

{

       public sealed void Show() 

       {

 

       } 

} 

  

class Class3 : Class2 

{ 

        //it is invalid because this method is sealed in Class2 class 

        public override void Show() 

        {

 

        } 

}