InvalidCastException on convertion to base Interface

When a class is assigned to an object and you want to cast the object value to an inherited interface of the original class, an InvalidCastException is raised. For the life of me, I cannot figure out why. I am new to NetMF code, so I am assuming that I am doing something very wrong.

This works in the normal .Net code.


Option Explicit On
Option Strict On

Imports Microsoft.SPOT

Namespace InterfaceTest

  Public Module Module1

    Sub Main()

      Dim obj As Object
      Dim test As IBase
      Dim level1 As ILevel1
      Dim local As New Level1

      ' Exercise the instances.
      local.BaseTest()

      level1 = local
      level1.BaseTest()

      test = level1
      test.BaseTest()

      ' Assign to object.
      obj = local

     ' Cast to direct interface. This works.
      Dim test2 As ILevel1 = CType(obj, ILevel1)
      test2.BaseTest()

      ' Cast to base interface. This throws InvalidCastException.
      Dim test3 As IBase = CType(obj, IBase)
      test3.BaseTest()

    End Sub

  End Module



  Public Interface IBase
    Sub BaseTest()
  End Interface


  Public Interface ILevel1
    Inherits IBase

  End Interface


  Public Class Level1
    Implements ILevel1

    Public Sub BaseTest() Implements IBase.BaseTest
      Debug.Print("Base Test")
    End Sub


    Public Sub LocalTest()
      Debug.Print("Local Test")
    End Sub
  End Class

End Namespace

Hi Marius, welcome to the Forums.

I think you have found a bug in the NETMF IL interpreter. This works perfectly well in C#, and the difference is in what the C# compiler does with the interface inheritance vs what the VB compiler does.

The C# compiler explicitly implements the interface hierarchy

For example


interface ILevel1 
{
  ...
}

interface ILevel2
{
  ...
}

class Level : ILevel2
{
  ...
}

Actually becomes, if you look at the IL


  class Level : ILevel2, ILevel1
  { 
     ...
  }

Where as the VB compiler emits IL that is true to the source code


  class Level : ILevel2
  { 
     ...
  }

So it would seem that the .NETMF IL interpreter is not looking at the interface inheritance hierarchy when performing type casts and conversions, it is rather relying on the compiler to emit IL that makes the hierarchy explicit and this fails in the case of the VB compiler.

You should report this to Microsoft as a potential bug/shortcoming.
http://netmf.codeplex.com

Thanks! Not what I really wanted to hear, but so be it :slight_smile:

Issue logged at NetMF Codeplex (Issue 1818).

I can imagine that was not what you wanted to hear. I will go up vote the issue.