Spot the bug

You might run into this one from time to time. I know it has bitten a LOT of people and it’s not intuitive at all.

In a new desktop app add a new Class. The default name of Class1 will work fine. And create a new subclass of this. Again the default of CustomClass1 will work fine.

Then in the default window add the open event handler. In there put these few lines of code.

Dim c As Class1
c = methodThatCreatesSubclassInstance
foo(c)

Then add two methods to Window1

The first should be defined as

Private Function methodThatCreatesSubclassInstance() as Class1
  Return New CustomClass1
End Function

And then we need two versions of Foo

Private Sub foo(c as Class1)
  Break
End Sub

Private Sub foo(c as CustomClass1)
  Break  
End Sub

Thats it. If you run this you might think that because methodThatCreatesSubclassInstance returns a CustomClass1, which you can see in the debugger at runtime, that the sub that takes a CustomClass1 would be the one that is called.

And you might try various tricks to make that happen like changing the return type of methodThatCreatesSubclassInstance to be CustomClass1.

Short of explicitly casting, which you really might want to avoid, you’ll find that the version of Foo that takes a Class1 parameter is the one that gets called.

And this is something I’ve long considered a bug. But various compiler engineers have disagreed 🙁

The important thing here is not the runtime type that the variable c holds. At runtime you can inspect it and see that it has exactly what we expected – an instance of CustomClass1.

What IS important is the declared type of c – a Class1. And the compiler decides, at compile time, that the version of Foo that should be used is the one that has a Class1 parameter.

Careful out there.