Reputation: 5171
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
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
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
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
Reputation: 878
requiredInterface.IsAssignableFrom(representedType)
both requiredInterface and representedType are Types
Upvotes: 4
Reputation: 16719
Use TypeOf...Is:
If TypeOf objectParameter Is ISpecifiedInterface Then
'do stuff
End If
Upvotes: 68