c# behavior on interface implementation

Viewed 1018

I've found a behaviour in c# and I would like to know if it's in the specs (and can be expected to work on all platforms and new versions of the .NET runtime) or if it's undefined behaviour that just happens to work but may stop compiling at any time.

So, let's say I want to take existing classes, like these:

public class HtmlTextBox
{
  public string Text {get; set;}
}

public class HtmlDiv
{
  public string Text {get; set;}
}

now I would really like them to implement a common IText interface, like this one:

public interface IText 
{
  string Text {get; }   
}

but I can't change the classes directly because they are part of an external library. Now there are various ways to do this, through inheritance or with a decorator. But I was surprised to find out that doing simply this compiles and works on .NET 4.5 (windows 7 64 bits).

public class HtmlTextBox2 : HtmlTextBox, IText {}
public class HtmlDiv2 : HtmlDiv, IText {}

That's it. This gets me drop-in replacements for HtmlTextBox and HtmlDiv that use their existing Text property as implementation for IText.

I was half-expecting the compiler to yell at me, asking me to provide an explicit re-implementation of Text, but on .NET 4.5 this just works:

IText h2 = new HtmlTextBox2{Text="Hello World"};
Console.WriteLine(h2.Text);  //OUTPUT: hello world

In fact,I've tried the same on mono (whatever version ideone.com is using) and mono does not yell at me either

So I guess I'm good to go, but before trying this on serious code I wanted to check if I've misunderstood what is really happening here or if I can't rely on this to work.

2 Answers
Related