views:

231

answers:

5
+4  Q: 

C# inheritance

Let's say I have the following code:

interface ISomeInterface
{
    void DoSomething();
    void A();
    void B();    
}

public abstract class ASomeAbstractImpl : ISomeInterface
{
    public abstract void A();
    public abstract void B();
    public void DoSomething()
    {
        // code here
    }
}

public class SomeImpl : ASomeAbstractImpl 
{
    public override void A()
    {
        // code
    }

    public override void B()
    {
        // code
    }
}

The problem is that i wish to have the ASomeAbstractImpl.DoSomething() method sealed (final) so no other class could implement it. As the code is now SomeImpl could have a method called DoSomething() and that could be called (it would not override the method with the same name from the abstract class, because that's not marked as virtual), yet I would like to cut off the possibility of implementing such a method in SomeImpl class.

Is this possible?

+8  A: 

Methods in C# are sealed by default. There is, however, nothing you can do to prevent method hiding (exposing a method with the same name in the derived class, commonly with new).

Or, for that matter, interface-reimplementation:

static void Main()
{
    ISomeInterface si = new EvilClass();
    si.DoSomething(); // mwahahah
}

public class EvilClass : ASomeAbstractImpl, ISomeInterface
{
    public override void A() {}
    public override void B() { }
    void ISomeInterface.DoSomething()
    {
        Console.WriteLine("mwahahah");            
    }
}
Marc Gravell
+2  A: 

All methods are sealed by default, but there's no way of preventing Member Hiding.

The C# compiler will issue a compiler warning whenever you hide a member, but apart from that, you can't prevent it.

Mark Seemann
It will only issue a warning if you do it by accident; add the "new" qualifier and it shuts up...
Marc Gravell
A: 

A method which is not marked as virtual is sealed by default. In a derived class you have to mark a "overriding" method with the keyword new, else you'll get a compiler warning. If the method of the super class is marked as virtual, you can seal it per sealed override.

http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx

Enyra
A: 

if SomeImpl class contains DoSemthing method, this means it hides the original one not override.

Ahmed Said
A: 

When dealing with interfaces and abstract classes its more about what you MUST do and not what you cannot do. So you can let the interface user know that these are the methods they must implement and with your abstract classes you can use the virtual keyword to let them know its OK to override a method. However you can't stop them from doing too much. Even if you purposefully don't use the virtual keyword they can still hide it with the new keyword.

Mark