Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / August 2007

Tip: Looking for answers? Try searching our database.

Determining if a type implements a particular interface

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Mario Vargas - 13 Aug 2007 17:49 GMT
Hello all,

When using reflection, how can I find out if a particular type implements a
specific interface. For instance, I have the following code:

  Type t = myAsm.GetType( "AssemblyToLoad.MyClass" );
  Type iMyClassType = typeof(AssemblyToLoad.IMyClass);
  foreach( Type i in t.GetInterfaces() )
  {
   Console.WriteLine( "Interface: {0}; Implemented: {1}, {2}",
    i,
    iMyClassType,
    i.Equals( iMyClassType ) );
  }

The type "AssemblyToLoad.MyClass" implements an interface called
"AssemblyToLoad.IMyClass", but the test "i.Equals( iMyClassType )" always
returns false. The code above is in a different assembly from the
"AssemblyToLoad" namespace.

Thanks for your help and tips...

Mario
Mattias Sjögren - 13 Aug 2007 19:25 GMT
>When using reflection, how can I find out if a particular type implements a
>specific interface. For instance, I have the following code:
>
>   Type t = myAsm.GetType( "AssemblyToLoad.MyClass" );
>   Type iMyClassType = typeof(AssemblyToLoad.IMyClass);

Why are you using Assembly.GetType for the class and typeof for the
interface if they are both defined in the same assembly?

Is there any chance you have two separate definitions of the IMyClass
interface?

BTW I like to use Type.IsAssignableFrom rather than looping through
all interfaces.

Mattias

Signature

Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Mario Vargas - 13 Aug 2007 19:53 GMT
The class AssemblyToLoad.MyClass and interface AssemblyToLoad.IMyclass are
defined in an assembly different from my client application.

I am emperimenting with loading a class defined in a separate assembly from
my client application that shares a common interface type. In my example,
that common interface is IMyClass. What I would like to do is create a
system where different implementations of an interface I am desigining can
be loaded at runtime using reflection or any other means. Reflection is a
new field for me.

I am also trying to use the Activator.CreateInstanceFrom( string, string )
method to accomplish my goal in a much more concise manner, but I get an
InvalidCastException. I am duplicating the example code shown in the
documentation for the Activator.CreateInstanceFrom(string, string, object[])
overloaded method.

I don't think I have two separate definitions of the same interface. I'll
check again.

I'll look at the documentation for Type.IsAssignableFrom. Thanks so much for
sharing that tip.

Mario

> >When using reflection, how can I find out if a particular type implements
> >a
[quoted text clipped - 13 lines]
>
> Mattias
UL-Tomten - 13 Aug 2007 22:32 GMT
> loading a class defined in a separate assembly [...] create a system where
> different implementations of an interface I am desigining can be loaded
> at runtime using reflection [...] use the Activator.CreateInstanceFrom([...])
> [...] InvalidCastException.

Just to reassure you: this is a pretty standard way to do it. It's
sometimes called the object builder pattern, I think. If you get
casting errors, make sure your references are correct, and that you
have no redundant DLLs, or old DLLs lying around, accidentally being
used. If you load an existing assembly from disk, make sure you
specify the correct assembly details.

This is a typical scenario with three assemblies, from the top of my
head:

1. ObjectBuilder assembly references assembly which contains IClass
and assembly which contains Class
2. Client assembly references assembly which contains IClass and
assembly which contains IClass
3. Client does IClass classInstance = ObjectBuilder<IClass>.Build(),
upon which ObjectBuilder uses reflection to CreateInstance() of Class,
casting it as IClass, and returning it.

I've used a shortcut from System.Web.dll sometimes:

http://msdn2.microsoft.com/en-us/library/system.web.compilation.buildmanager_met
hods.aspx


It does iteration over assemblies and types to find a specified type,
which you might end up doing yourself otherwise, if you want a real
System.Type.
Mario Vargas - 14 Aug 2007 20:32 GMT
Thank you all for your contributions!

>> loading a class defined in a separate assembly [...] create a system
>> where
[quoted text clipped - 28 lines]
> which you might end up doing yourself otherwise, if you want a real
> System.Type.
Kevin Spencer - 14 Aug 2007 12:50 GMT
Use the "is" operator:

if (i is iMyClassType) ...

Signature

HTH,

Kevin Spencer
Microsoft MVP

DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net

> Hello all,
>
[quoted text clipped - 19 lines]
>
> Mario
Mattias Sjögren - 14 Aug 2007 15:10 GMT
>Use the "is" operator:
>
>if (i is iMyClassType) ...

Not in this case, where iMyClassType is a System.Type instance.

Mattias

Signature

Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

UL-Tomten - 14 Aug 2007 15:31 GMT
On Aug 14, 4:10 pm, Mattias Sj?gren <mattias.dont.want.s...@mvps.org>
wrote:

>> if (i is iMyClassType) ...
>
> Not in this case, where iMyClassType is a System.Type instance.

Also, the correct form is "i am", not "i is". The new Code Analysis in
Visual Studio 2008 would generate a OperatorShouldBeVerbedCorrectly
warning for this error.
Ged - 14 Aug 2007 15:49 GMT
Since when has "am" been a keyword in C#/.Net ?
I think you've misread the code slightly. Something more readable might be :

public void DoSomething(object obj)
{
   if( obj is iMyClassType )
   {
   }
}

HTH

Ged

On Aug 14, 4:10 pm, Mattias Sjögren <mattias.dont.want.s...@mvps.org>
wrote:

>> if (i is iMyClassType) ...
>
> Not in this case, where iMyClassType is a System.Type instance.

Also, the correct form is "i am", not "i is". The new Code Analysis in
Visual Studio 2008 would generate a OperatorShouldBeVerbedCorrectly
warning for this error.

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.