Strange Interface Behaviour in VB.Net vs. C#
Most of my recent examples have been in VB.Net to benefit the students in my class, but I program more often in C#. Take the following VB.Net code:
Shared Sub Main()
dim obj as ILoggable = new PersonObject()
MessageBox.Show( obj.ToString() )
End Sub
Public Interface ILoggable
Sub LogState()
End Interface
Public Class PersonObject
Implements ILoggable
Public Sub LogState() Implements ILoggable.LogState
'log Person state to the Person table, text file, whatever
End Sub
End Class
This doesn’t compile in VB.Net because of the obj.ToString() method call.
Now consider the following C# code:
[STAThread]
static void Main()
{
ILoggable obj = new personObject();
MessageBox.Show( obj.ToString() );
}
public class personObject: ILoggable
{
public void LogState()
{
//nothing
}
}
public interface ILoggable
{
void LogState();
}
Fasten your seat belts, the C# compiles and runs; it displays “personObject” in the dialogbox when MessageBox.Show( obj.ToString() ) is called. C# Interfaces behave as if they derive from System.Object, while VB.Net interfaces do not. Where is the interoperability? Yikes. This makes Interfaces in C# more powerful since you can interrogate via Reflection. Try:
MessageBox.Show( obj.GetType().ToString() );
And you’ll see what I’m getting at (it displays the type name personObject).
Score 1 (maybe 2, if you’ve created an elaborate reflection-dependent design) for C#. Anyone have any insight into why this is?