Sealed class in c# with real time example

Sealed classes and Sealed
methods in C#.NET

Introduction
of Sealed class:A sealed class is a class that does not allow inheritance.
Some object model designs need to allow the creation of new instances but not
inheritance, if this is the case, the class should be declared as sealed.To
create a sealed class in C#, the class declaration should be done as:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

sealedclassSealedClass// Sealed class

{

publicint Add(int x, int y)

{

return x + y;

}

}

classClass1 : SealedClass

{

staticvoid Main(string[]
args)

{

SealedClass sealedCls = newSealedClass();

//Object
creation of sealed class

int total = sealedCls.Add(4, 5);

//Calling
the function

Console.WriteLine("Total
= " + total.ToString());

}

}

When you try to derive a class from sealed class compiler
throw an error."'Class1': cannot derive from sealed type 'SealedClass'
"

The actual mean of using sealed class is to prevent
inheritance of a class, we do not want to allow some class to extend the
functionality of a class.

*Sealed class is like the normal class but the sealed class can't
inherited but it's possible can be instantiated like normal class.

*To declare sealed class we should use the sealed keyword with the
class declaration.

*The sealed classes are useful in order to protect our classes not
to be used by any other classes.

Sealed Method:

We can also use the sealed modifier on a method or property that
overrides a virtual method or property in a base class. If we want to stop the
derivation of class for the next level then we need to mark method as sealed in
previous class.