Marco Bettiolo
Marco Bettiolo

Reputation: 5171

Test if an object implements an interface

I have an object parameter and I need to check if the object implements a specified interface in vb.net. How to test this?

Thanks.

Upvotes: 48

Views: 17882

Answers (5)

Harold Short
Harold Short

Reputation: 191

Here is a simple way to determine whether a given object variable "o" implements a specific interface "ISomething":

If o.GetType().GetInterfaces().Contains(GetType(ISomething)) Then
    ' The interface is implemented
End If

Upvotes: 4

Elmer
Elmer

Reputation: 135

I have a List(Of String) and the TypeOf tmp Is IList returns False. A List(Of T) implements multiple interfaces (IEnumerable, IList, ...) and checking just one requires the following snippet in VB:

If tmp.GetInterfaces().Contains(GetType(IEnumerable)) Then
  // do stuff...
End If

Upvotes: 0

Nick DeVore
Nick DeVore

Reputation: 10166

I also found this article by Scott Hansleman to be particularly helpful with this. In it, he recommends

C#

if (typeof(IWhateverable).IsAssignableFrom(myType)) { ... }

I ended up doing:

VB.Net

Dim _interfaceList As List(Of Type) = myInstance.GetType().GetInterfaces().ToList()
If _interfaceList.Contains(GetType(IMyInterface)) Then
   'Do the stuff
End If

Upvotes: 8

Joe Caffeine
Joe Caffeine

Reputation: 878

requiredInterface.IsAssignableFrom(representedType)

both requiredInterface and representedType are Types

Upvotes: 4

AJ.
AJ.

Reputation: 16719

Use TypeOf...Is:

If TypeOf objectParameter Is ISpecifiedInterface Then
    'do stuff
End If 

Upvotes: 68

Related Questions