Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET Interface Instantiation Oddity

I was looking through some legacy code we have and I noticed something that struck me as particularly odd.

Say we have the concrete class TestClass. TestClass implements the interface ITestClass.

What sort of behavior should I expect in the following case, then? (I didn't realize this was even possible)

Dim testClass as TestClass = Nothing
Try
   testClass = New ITestClass
   ...
End Try

As far as I understand, you would be FORCED to utilize TestClass instead of its interface counterpart.

like image 632
Joe Morgan Avatar asked Jan 24 '12 14:01

Joe Morgan


1 Answers

There's one special case, where an interface can be instantiated like a class, and it's related to the CoClassAttribute. See this blog post for details:

  • Unnatural acts on source code: Instantiating interfaces

Example from the blog post translated to VB:

<ComImport(), Guid("C906C002-B214-40d7-8941-F223868B39A5"), CoClass(GetType(Foo))> _
Public Interface IFoo
End Interface

Public Class Foo
    Implements IFoo
End Class

Sub Main()
    Dim f As New IFoo()    ' Compiles
End Sub
like image 65
Heinzi Avatar answered Nov 07 '22 11:11

Heinzi