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.
Join Stack Overflow to learn, share knowledge, and build your career.
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.
Use TypeOf...Is:
If TypeOf objectParameter Is ISpecifiedInterface Then
'do stuff
End If
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
requiredInterface.IsAssignableFrom(representedType)
both requiredInterface and representedType are Types
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
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