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;
sealed class SealedClass   // Sealed class
{
    public int Add(int x, int y)
    {
        return x + y;
    }
} 
class Class1 : SealedClass
{
    static void Main(string[] args)
    {
        SealedClass sealedCls = new SealedClass();
      //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.

Advantages of sealed class in c# 
1.Sealed keyword in C# applies restrictions on the class and method
2.At class level sealed modifier prevents a class from being inherited. 

Some true fact about a sealed class in c#

* Can we create instance of sealed class in c#
   Yes, you can

* Purpose of sealed class in c# net
  Is to prevent class being inherit

* 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.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SealedClass
{
    class Boss
    {
        virtual public void Work()
        {
            Console.WriteLine("In class A");
        }
    }

    class TL : Boss
    {
        sealed override public void Work()
        {
            Console.WriteLine("In class B");
        }
    }
    class Employee : TL
    {
        override public void Work() //Error: cannot override inherited member 
        {                               //TL.Work() because it is sealed  

        }
    }
}


 Also Read:






Previous
Next Post »