What is a sealed class in C# and why do programmers use the sealed class in C# program?

Asked 26-Aug-2021
Updated 26-Aug-2021
Viewed 620 times

0

What is a sealed class in C# and why do programmers use the sealed class in C# program?


1 Answer


0

Sealed Class in C#
 Just as Abstract Class is always required to be Derived Compulsory, similarly many times we want that any class we create cannot be inherited anymore. That is, when we want to define a class as the last of the Inheritance Hierarchy, then we give instructions to the C# compiler by using the sealed keyword with the name of such class that the Sealed Class cannot be further inherited. Can, as a result, if we try to derive a Sealed Class, the C# compiler prevents us from doing so by generating an error. In other words, we can never use a Sealed Class as a Base Class.
Syntax
// sealed class syntax
sealed class class-name{  . . . }
// sealed method syntax
class class-name{  public sealed datatype method-name(){   . . .  } }
If we specify the sealed keyword with a class named MyClass in this way, then we cannot inherit MyClass in any case and inherit its features in the new class. But sometimes the situation is such that we do not want to seal the entire class. That is, we do not want to prevent the whole class from being Derived, but we want that any Virtual Method defined in the Base Class cannot to be overridden in the Derived Class. In this case, we don't use sealed keywords with Class, but only specify sealed modifiers with Method which we want to prevent from being overridden in Derived Class.
Example 
using System;
sealed class SealedDemoClass{
 public void PrintSum(int first,int second)
 {
  Console.WriteLine('Sum : {0}',(first+second));
 }
}
public class Program
{
 public static void Main()
 {
  SealedDemoClass sdc=new SealedDemoClass();
  sdc.PrintSum(45,25);
 }
}

Output

Sum : 70
Another example of sealed class 
using System;

sealed class SealedDemoClass{
 public void PrintSum(int first,int second)
 {
  Console.WriteLine('Sum : {0}',(first+second));
 }
}
class SealedDerived: SealedDemoClass{
}

public class Program
{
 public static void Main()
 {
  SealedDemoClass sdc=new SealedDemoClass();
  sdc.PrintSum(45,25);
 }
}

Compile-time Error

Compilation error (line 9, col 7): 'SealedDerived': cannot derive from sealed type 'SealedDemoClass'

Can't override the sealed class in the derived class only use the singleton class.