This chapter is from the book
Prevent Inheritance
Scenario/Problem: |
You want to prevent users of your class from inheriting from it. |
Solution: |
Mark the class as sealed. sealed class MyClass { ... } |
Structs are inherently sealed.
Prevent Overriding of a Single Method
Scenario/Problem: |
You don’t want to ban inheritance on your type, but you do want to prevent certain methods or properties from being overridden. |
Solution: |
Put sealed as part of the method or property definition. |
class ParentClass { public virtual void MyFunc() { } } class ChildClass : ParentClass { //seal base class function into this class public sealed override void MyFunc() { } } class GrandChildClass : ChildClass { //yields compile error public override void MyFunc() { } }