check if object implements interface not working ;/

J

Jon Slaughter

I wrote this function that is suppose to returnt rue if an array of
types(actually stuff returned by GetInterfaces) implements the interface Q.


private bool ContainsInterface<A, Q>(A[] list)
{
foreach (A a in list)
if (a is Q)
return true;
return false;
}

and is used like

ContainsInterface<Type, IEnumerable>(field.FieldType.GetInterfaces()))



So it checks the list for elements that implement IEnumerable.



I used this successfully in a "ContainsType"



ContainsType<Attribute, RawExcludeAttribute>(attributes)



Where its the same code. The above essentially just checks if any of the
attribute's in attributes is a RawExcludeAttribute. It works fine. My logic
was the same for interfaces but it doesn't work. (Maybe interfaces cannot
implement themselfs as "a is Q" is always false... yet when I debug I get
exactly these type for a and typeof(Q).

Even something like

foreach (A a in list)

{

Type t = typeof(Q);

if (a.GetType() == typeof(Q))

return true;

}



does not work.



In this case

t = + t {Name = "IEnumerable" FullName = "System.Collections.IEnumerable"}
System.Type {System.RuntimeType}
a = + a {Name = "IEnumerable" FullName = "System.Collections.IEnumerable"}
System.Type {System.RuntimeType}


So I don't see why they are not the same types ;/



Thanks,

Jon
 
J

Jon Slaughter

In this case

t = + t {Name = "IEnumerable" FullName =
"System.Collections.IEnumerable"} System.Type {System.RuntimeType}
a = + a {Name = "IEnumerable" FullName =
"System.Collections.IEnumerable"} System.Type {System.RuntimeType}


So I don't see why they are not the same types ;/


I do see something like a.GetType().ToString() always returns the RunTime
Type and that is probably the reason why its not working but I don't see how
to fix it.
 
J

Jon Slaughter

NM, was being stupid on what I was doing. Was checking to see if the
interfaces contained an interface but all I had to do was check and see if
the object itself implemented it(using is).
 
M

Morten Wennevik [C# MVP]

Jon Slaughter said:
NM, was being stupid on what I was doing. Was checking to see if the
interfaces contained an interface but all I had to do was check and see if
the object itself implemented it(using is).

Indeed, if you have an object this should work fine

if(myObject is IEnumerable) { ... }

If, however, you only have the types then something like this should work

public bool ContainsInterface(Type A, Type Q)
{
Type[] interfaces = A.GetInterfaces();
foreach (Type type in interfaces)
{
if (type == Q)
return true;
}

return false;
}
 

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