C# Sealed

C# provides sealed keyword to apply restrictions on class and methods. If a class is defined as sealed then it can’t be inherited. If a method is defined as sealed then it can't be overridden. This is like final keyword of java. The main advantage of sealed class is that the third party vendor can't develop any software by inheriting our logic. Sealed class is the last class in the hierarchy. A base class can never be a sealed class rather we can apply sealed keyword to a derived class.


Sealed Class Example:
using System;
sealed public class Animal
{
            public void eat()
            {
                        Console.WriteLine("Eating ....");
            }
}
public class Dog:Animal
{
            public void eat()
            {
                        Console.WriteLine("Eating Bread...");
            }
}
public class SealedClassExample
{
            public static void Main(string[] args)
            {
                        Dog d=new Dog();
                        d.eat();
            }
}
Output
Compilation error (line 9, col 14): 'Dog': cannot derive from sealed type 'Animal'
C# Sealed Method Example:
using System;
 public class Animal
{
            public virtual void eat()
            {
                        Console.WriteLine("Eating ....");
            }
}
public class Dog:Animal
{
            sealed public override void eat()
            {
                        Console.WriteLine("Eating Bread...");
            }
}
public class BabyDog:Dog
{
            public override void eat()
            {
                        Console.WriteLine("Eating dogfood...");
            }
}
public class SealedClassExample
{
            public static void Main(string[] args)
            {
                        Dog d=new BabyDog();
                        d.eat();
            }
}
Output 
Compilation error (line 18, col 23): 'BabyDog.eat()': cannot override inherited member 'Dog.eat()' because it is sealed