Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an object implements an interface

Tags:

vb.net

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.

like image 939
Marco Bettiolo Avatar asked Sep 01 '09 02:09

Marco Bettiolo


People also ask

How do you check if an object implements an interface?

Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.

Can an object implement an interface?

If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. By casting object1 to a Relatable type, it can invoke the isLargerThan method.

How do I know if a class has an interface?

isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.


4 Answers

Use TypeOf...Is:

If TypeOf objectParameter Is ISpecifiedInterface Then
    'do stuff
End If 
like image 169
AJ. Avatar answered Oct 01 '22 05:10

AJ.


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
like image 25
Nick DeVore Avatar answered Oct 01 '22 06:10

Nick DeVore


requiredInterface.IsAssignableFrom(representedType)

both requiredInterface and representedType are Types

like image 32
Joe Caffeine Avatar answered Oct 01 '22 05:10

Joe Caffeine


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
like image 34
Harold Short Avatar answered Oct 01 '22 04:10

Harold Short