This blog has moved!

Check out www.CodeBetter.com/blogs/grant.killian

<May 2008>
SuMoTuWeThFrSa
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567


Navigation

Professional Props...

Extracurricular Props...

Subscriptions

Article Categories



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?

posted on Wednesday, August 27, 2003 7:57 AM by grant.killian





Powered by Dot Net Junkies, by Telligent Systems