Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# interface and inheritance question

I am learing C# (C++ background), and I have come accross this piece of code:

public interface IUndoable { void Undo(); }
public class TextBox : IUndoable
{
    void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); }
}

public class RichTextBox : TextBox, IUndoable
{
    public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}

Since RichTextBox derives from TextBox, can anyone explain why RichTextBox is also deriving from IUndoable?. I would have thought that the IUndoable interface will be "inherited along" with any other TextBox members that RichTextBox has access to?

As an aside, I am guessing from what I have read so far, that the concept of public, protected and private inheritance does not exist in C#.

Is this a correct inference?. If so, how may such behavior (i.e. restricting inheritance) be implemented in C#?

[Edit]

Clarification: The section in the book I am reading is about the subtle differences and potential gotchas of implicit and explicit interface implementations - so I get that. Also, the code snippet (copied from the book) is intentionally verbose, so as to explain the differing semantics that ensues as a result of invoking a reimplemented member method that was implicitly implemented in the base class (phew!).

My main question can simply be summarized as:

Could this:

public class RichTextBox : TextBox, IUndoable
{
    public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}

Be written as:

public class RichTextBox : TextBox
{
    public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}

And if yes, why is the Author being verbose (he must have a reason I'm sure). If no, why is the interface not being inherited from TextBox?

like image 672
voidstar Avatar asked May 18 '11 07:05

voidstar


1 Answers

In C#, for classes, there is only the equivalent of public inheritance in C++.

You can, however, implement an interface explicitly or implicitly. TextBox implements IUdoable explicitly, that's why you have

void IUndoable.Undo() 

instead of simply

void Undo() 

in your TextBox class. When an interface is implemented explicitly, you can access the interface's methods on the object only through an explicit cast:

TextBox tb = new TextBox();
tb.Undo(); // error
((IUndoable)tb).Undo(); // ok

Interfaces are, as you say, "inherited along", but RichTextBox re-implements IUndoable implicitly, so you don't need the cast to access the interface's methods:

RichTextBox rtb = new RichTextBox();
rtb.Undo(); // ok
like image 79
Paolo Tedesco Avatar answered Oct 20 '22 14:10

Paolo Tedesco