Alexej Alexej - 3 months ago 17
C# Question

Inheritance and sealed

Should I always specify a class as sealed if it's the last in the inheritance list? As an example, say I've got 3 classes,

Foundation
,
Building
, and
House
.

public class Foundation
{
// Base class
}

public class Building : Foundation
{
// Derived from Foundation
}

public sealed class House : Building
{
// Last in the inheritance tree
}


Is it about safety when I say that I don't want anyone to inherit from House while House itself is inheriting from
Building
?

Answer

Let's say you have a MyDivisor class with SetDivisor and GetDivisor methods. The SetDivisor method is implemented as follows:

public void SetDivisor(int divisor)
{
    if (divisor != 0)
    {
        _divisor = divisor; // `_divisor` is a field of the class
    }
}

Even though you might think there is no way of the divisor being zero, someone might inherit your MyDivisor class and use the new keyword to hide your method (which is not virtual). The derived MyEvilDivisor class has the following implementation of SetDivisor:

new public void SetDivisor(int divisor)
{
    _divisor = divisor;
}

Now someone can write:

var divisor = new MyEvilDivisor();
divisor.SetDivisor(0);
int i = 5/(divisor.GetDivisor());

If you seal your class, there will be no way to inherit it and change the behavior of SetDivisor, which will not lead to unexpected runtime errors in the application that will surely happen when using MyEvilDivisor. I guess this is an example of thinking about safety.

Comments