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

Sealed Class in C#

In the C#, Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword.

C# sealed keyword applies restrictions on the class and method. If we create a sealed class, it cannot be derived. If we create a sealed method, it cannot be overridden.


C# Sealed class

using System;  

 sealed public class Animal{
    public void eat() { Console.WriteLine("eating..."); }
}
public class Cat: Animal
{
    public void bark() { Console.WriteLine("barking..."); }
}
public class SealedExample
{
    public static void Main()
    {
        Cat objCat = new Cat();
        objCat.eat();
        objCat.bark();
    }
}  

Output

Compilation error (line 5, col 14): 'Cat': cannot derive from sealed type 'Animal'


C# Sealed method

using System;  

public class Animal{
    public virtual void eat() { Console.WriteLine("eating..."); }
    public virtual void run() { Console.WriteLine("running..."); }
}
public class Cat: Animal
{
    public override void eat() { Console.WriteLine("eating bread..."); }
    public sealed override void run() {
    Console.WriteLine("running very fast...");
    }
}
public class BabyCat: Cat
{
    public override void eat() { Console.WriteLine("eating biscuits..."); }
    public override void run() { Console.WriteLine("running slowly..."); }
}
public class TestSealed
{
    public static void Main()
    {
        BabyCat obj = new BabyCat();
        obj.eat();
        obj.run();
    }
}  

Output

Compilation error (line 17, col 26): 'BabyCat.run()': cannot override inherited member 'Cat.run()' because it is sealed



using System;  

public class SealedExample
{
    public static void Main()
    {
        sealed int number = 10;
        number++;
        Console.WriteLine(number);
    }

Output

Compile Time Error: Invalid expression term 'sealed'