find and solve || findandsolve.com
Please wait.....

What is Sealed Class Example in C#? Who to use in C#


               Sealed Class Example in C#

The sealed keyword used in c# language is used to create a sealed class.This Sealed classes restrict  inherit a class.Sealed classes are used to restrict the inheritance  of OOP[object oriented programming]. class can not be derived from a sealed class.It cannot be used as a base class because  it cannot also be an abstract class. If a sealed class is derived,compiler throws an error.

The syntax of a sealed class :

sealed class <Your-Sealed-ClassName>
{
    // data members
    // methods
    .
    .
    .

}

This method can also be sealed and in that case,the method cannot be overridden.
In the classes,a method can be sealed in which they have been inherited.If you want to declare 
a method as sealed,it has to be declared as virtual base class.


This class definition defines a sealed class in C#

// Sealed class 
sealed class SealedClassExample
{
}

Sealed Class Example in C#

using System;  
namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            SealedClassExample obj = new SealedClassExample();
            string str = obj.Display();

            Console.WriteLine(str);
            Console.ReadLine();
        }
    }

    public sealed class SealedClassExample
    {
        public string Display()
        {
            return "Perfect";
        }
    }
}

Sealed Methods and Properties

class A
{
    protected virtual void S()
    {
        Console.WriteLine("A.S");
    }
    protected virtual void S1()
    {
        Console.WriteLine("A.T4");
    }
}
class B : A
{
    sealed protected override void S()
    {
        Console.WriteLine("B.S");
    }
    protected override void S1()
    {
        Console.WriteLine("B.U2");
    }
}
class C : B
{
    // Attempting to override S causes compiler error   
    //this erro has been occured 'C.S()':cannot override inherited member 'B.S()' because it is sealed  
    protected override void S()
    {
        Console.WriteLine("D.S");
    }
    // Overriding F2 is allowed.   
    protected override void S1()
    {
        Console.WriteLine("C.S1");
    }
}

Why We use Sealed Classes in C#?

⦁Stop a class to be inherited and cannot derive any class.

⦁If sealed method is implemented,other class can not overthrow it and implement its own method.

⦁Withdraw the inheritance attribute from a sealed class. When you have a class with static members 
you can used sealed classes are best.

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response