Search code examples
c#.netcastingdowncast

Prohibit downcasts of base class


Downcasts are a code smell. Implementing a base class; is there a way in C# to prevent the base class or interface from being downcasted by inheriting classes? The capability to derive from the base class should be preserved.

Example

interface IFoo { /* ... */ } // Only this interface can be modified.

class Bar : IFoo { /* ... */ }

void doSthWith(IFoo f)
{
    Bar b = (Bar) f; // to prohibit
}

Solution

  • No

    I won't argue with you on the code smell, but you can always attempt a downcast (it may of course, fail) from a base class to a derived class.

    Even if it were possible, there are valid downcasting scenarios and if this is in a library, you would be restricting potential users.

    See the casting article on MSDN for more info.

    From the C# 5.0 Spec:

    A cast-expression is used to explicitly convert an expression to a given type. cast-expression: ( type ) unary-expression A cast-expression of the form (T)E, where T is a type and E is a unary-expression, performs an explicit conversion (§6.2) of the value of E to type T. If no explicit conversion exists from E to T, a binding-time error occurs. Otherwise, the result is the value produced by the explicit conversion. The result is always classified as a value, even if E denotes a variable.

    For an explicit reference conversion to succeed at run-time, the value of the source operand must be null, or the actual type of the object referenced by the source operand must be a type that can be converted to the destination type by an implicit reference conversion (§6.1.6) or boxing conversion (§6.1.7).

    There is more, but nothing that would indicate a method to restrict casting.