FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

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() { }

}

Total Pages : 12 89101112

comments