Joe Morgan
Joe Morgan

Reputation: 1771

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.

Upvotes: 5

Views: 371

Answers (1)

Heinzi
Heinzi

Reputation: 172270

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:

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

Upvotes: 8

Related Questions