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() { }
- The sealed modifier is used to prevent derivation from a class.
- An error occurs if a sealed class is specified as the base class of another class.
- A sealed class cannot be an abstract class.
- Sealed method enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
Example:
class A
{
protected virtual void show()
{
//Statements
}
}
class B : A
{
sealed protected override void shoe()
{
//Statements
}
}
{
protected virtual void show()
{
//Statements
}
}
class B : A
{
sealed protected override void shoe()
{
//Statements
}
}
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.