Search This Blog

Thursday, November 7, 2013

Sealed modifier C#

C# > Modifiers > sealed

Sealed modifier prevents other classes from inheriting from it.
Also you can use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

Examples

1. Sealed class
    class C1 { }
    sealed class C2 : C1 { }
    class C3 : C2 { } // Error : cannot derive from sealed type C2

2. Sealed method
    class A
    {
        protected virtual void F() { }
        protected virtual void F1() { }
    }
    class B : A
    {
        sealed protected override void F() { }
        protected override void F1() { }
    }
    class C : B
    {
        protected override void F() { } //Error cannot override inherited member because it is sealeD
        protected override void F1() { }
    }