Home All Groups Group Topic Archive Search About

Check Interface Implementation of a Type

Author
1 Apr 2006 9:15 AM
Hayato Iriumi
Hello folks,

I'm dynamically loading assembly by looping through types in the
assembly. But I want to load the types that implements a interface. So
the issue I'm having is whether I can check a type implements an
interface.

Of course, I could load the type by invoking CreateInstance of the
assembly and do TryCast, but I want to know whether the type implements
the interface before I load the type.

Author
1 Apr 2006 12:02 PM
Mattias Sjögren
>So the issue I'm having is whether I can check a type implements an
>interface.

Sure, check out the Type.IsAssignableFrom method.



Mattias

--
Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Author
1 Apr 2006 6:24 PM
Hayato Iriumi
Hello,
Hello, thank you very much for your reply.

I tried IsAssignableFrom myself, but it always returns false. I have an
Interface "ITest". And my "Customer" class implements "ITest". Here is
what I did...

    Sub Main()
        Dim cust As New Customer(1, "MyFirstName", "MyLastName")

Console.WriteLine(cust.GetType().IsAssignableFrom(GetType(ITest)))
        Console.Read()
    End Sub

I would expect IsAssignableFrom() function to return True, but it
return false. Am I doing something wrong?
Author
1 Apr 2006 6:56 PM
Branco Medeiros
Hayato Iriumi wrote:
<snip>
> I tried IsAssignableFrom myself, but it always returns false. I have an
> Interface "ITest". And my "Customer" class implements "ITest". Here is
> what I did...
<snip>
> Console.WriteLine(cust.GetType().IsAssignableFrom(GetType(ITest)))
<snip>
> I would expect IsAssignableFrom() function to return True, but it
> return false. Am I doing something wrong?

According to the docs, it seems you should be dowing:

  Console.WriteLine(GetType(ITest).IsAssignableFrom(cust.GetType()))

because A.IsAssignableFrom(B) will be true if B is a type that
implements A (and not the other way around)...

Regards,

Branco
Author
2 Apr 2006 2:06 AM
Hayato Iriumi
Yes, you're right about that. I tested it works now. Thank you very
much for your help!