Is vs IsAssignableFrom to detect and interface

D

djmc

Hi, I have an interface IMyInterface that is implemented by BaseClass. I
also have a class DerivedClass that is inherited from BaseClass.

Using reflection, I would like to be able to find DerivedClass by detecting
that it has implemented IMyInterface through BaseClass.

Here is my code to try and do so:

Call With:
------------
List<Type> ltTypes;
PluginLocator plLocator;
string sPath = @"c:\plugins\";

ltTypes = plLocator.FindTypesByInterface<IMyInterface>(sPath, "*.dll");
------------


FindTypesByInterface defined as:
------------
public List<Type> FindTypesByInterface<InterfaceType>(string path, string
searchpattern)
{
Assembly aAssembly;
Type[] tPossibleTypes;
List<Type> ltFoundTypes = new List<Type>();
string[] sAssemblies = Directory.GetFiles(path, searchpattern);

foreach (string sAssembly in sAssemblies)
{
aAssembly = Assembly.LoadFile(sAssembly);
tPossibleTypes = aAssembly.GetTypes();

foreach (Type type in tPossibleTypes)
{
//how come this DOES NOT work?
if (type is InterfaceType)
ltFoundTypes.Add(type);
else if (type.BaseType != null && type.BaseType is InterfaceType)
ltFoundTypes.Add(type);

//how come this DOES work?
//if (typeof(InterfaceType).IsAssignableFrom(type))
//
ltFoundTypes.Add(type);
}
}

return ltFoundTypes;
}
------------

As you can see, the is keyword does not detect the interface IMyInterface.
However, the method IsAssignableFrom does detect it. I was just curious why
this is and if I was using the is keyword incorrectly.

Thanks!
 
M

Mattias Sjögren

//how come this DOES NOT work?
if (type is InterfaceType)

It doesn't work because you're checking if the type of the "type"
variable, i.e. System.Type, implements InterfaceType.

//how come this DOES work?
//if (typeof(InterfaceType).IsAssignableFrom(type))

Why does that surprise you`? It should work.


Mattias
 
T

Truong Hong Thi

djmc said:
//how come this DOES NOT work?
if (type is InterfaceType)
"is" operator requires an instance of the type, not the type itself, on
its left side.
Thus, "is" operator is similar to Type.IsInstanceOfType, not
Type.IsAssignableFrom.

You can change that line to:
if (Activator.CreateInstance(type) is InterfaceType) // requires
parameterless constructor

However, IsAssignableFrom is clearly better in this situation.

Hope that helps,
Thi
 
D

djmc

Hi,

Thank you so much for your reply. I see what I wrote now was indeed
comparing a Type object with InterfaceType which was not what I meant to do.
I'll just stick with the IsAssignableFrom method.

Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top