Skip to main content

Posts

Showing posts from 2018

Sealed Classes and Sealed Methods

Sealed Class Sealed class is a special kind of class in C# which is used to prevent the inheritance to next level. Any class with sealed keyword cannot be derived to any subclass. We will get a compile error if we try to define base class as sealed class. sealed class A { } class B: A { } //CompileError In the above example if we see, Class B tries to inherit from class A which is sealed. We will get a compiler error. Now if we move the sealed keyword from Class A to Class B and try to inherit from class B we will get a compile error ( 'C': cannot derive from sealed type 'B' ). class A { } sealed class B: A { } class C : B { } //Compile Error Below code should be fine, as Sealed class should be the last in the inheritance hierarchy. class A { } class B : A { } sealed class C : B { } Sealed and Abstract modifiers cannot be used together as Abstract Class has to provide the functionality and Sealed will prevent that. Sealed class cannot