#621 – Sealing a Class to Prevent Inheritance
July 6, 2012 Leave a comment
By default, a public class may be inherited from–by a class within the same assembly or even by a class in a different assembly.
To prevent your class from being used as a parent class, you can declare the class with the sealed keyword. This “seals” the class, so that no one else can inherit from it.
public sealed class Dog { public void Bark() { Console.WriteLine("Dog barking: Woof"); } } // Compile-time error: Cannot derive from sealed type DogLibrary.Dog public class Terrier : Dog { }
A sealed class can’t be abstract–since the whole idea of an abstract class is that it is meant to serve as a base class for other classes.