views:

94

answers:

4

I was doing some code review today and came across an old code written by some developer. It goes something like this

public abstract class BaseControl
    {
        internal abstract void DoSomething();

    }

If you have a derived class within the same assembly, it would work

public class DerivedControl : BaseControl
    {
        internal override void DoSomething()
        {

        }
    }

But deriving the base class in a different assembly would give compile time error

DerivedControl does not implement inherited abstract member 'BaseControl.DoSomething()

That got me thinking. Why would anyone declare a method as internal abstract ?

+1  A: 

My initial reaction was that there is no good reason, if you want to prevent external inheritance then you should mark the class internal. But that means that the class is totally hidden to other assemblies.

I suppose this method prevents external inheritance while retaining visibility.

Paul Creasey
+1  A: 

One obvious case is where the method receives or returns an internal type. For example, the core methods of the WPF Transform classes process some internal interop types, which WPF doesn't expose as part of its public API. Because the signature includes internal types, the method can't be public or protected. And yet clearly it's appropriate (necessary!) for the various Transform classes to work polymorphically. Therefore the base methods in Transform/GeneralTransform have to be internal.

Another, but related reason is to prevent external derivation. After all, the WPF architects could have exposed a "safe" version of the internal interop types in a protected abstract method, so that users could create their own Transform classes. They didn't because they didn't want to have to cope with the ways that people might use that capability, e.g. creating non-affine transforms. Allowing external derivation would have made the job of other classes in WPF hugely more complex, so the architects decided to allow only "approved" derived classes by making an abstract method internal.

itowlson
+1  A: 

The original programmer wanted to make a derived control available to client code. But prevent the client from inheriting and messing with the virtual method. That's not a bad idea, it is usually easy to break a base class by overriding a method and doing something like forgetting to call the base class method.

Hans Passant
A: 

By defining a method as internal abstract you want to make sure that only the class in the same assembly can have its implementation for your method.

now if you distribute a dll of it this will avoid the client to inherit and mesup the implementation.

Vinay Pandey