Algorithm


In C#, the sealed keyword is used to prevent further derivation of a class or further overriding of a method in a derived class. When applied to a class, it means that the class cannot be used as a base class for other classes. When applied to a method, it means that the method cannot be overridden in derived classes.

 

Code Examples

#1 Code Example- Sealed Class in C#

Code - C# Programming

using System;
namespace SealedClass {
  sealed class Animal {
    
  }

  // trying to inherit sealed class
  // Error Code
  class Dog : Animal {
    
  }   

  class Program  {
    static void Main (string [] args) {

      // create an object of Dog class
      Dog d1 = new Dog();  
      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor

#2 Code Example- Sealed Method in C#

Code - C# Programming

using System;
namespace SealedClass {

  class Animal {
    public virtual void makeSound() {
    Console.WriteLine("Animal Sound");
    }
  }

  class Dog : Animal {

    // sealed method
    sealed public override void makeSound() {

      Console.WriteLine("Dog Sound");
    }
  }

  class Puppy : Dog {

    // trying to override sealed method
    public override void makeSound() {
      Console.WriteLine("Puppy Sound");
    }
  }   

  class Program  {
    static void Main (string [] args) {
      
      // create an object of Puppy class
      Puppy d1 = new Puppy();  
      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


C# Programming sealed class and method