Does a class implement an interface?

P

Peter Morris

interface Interface1
{
}

interface Interface2 : Interface1
{
}

class A : Interface2
{
}


static void Main(string[] args)
{
Console.WriteLine(typeof(A).IsSubclassOf(typeof(Interface1)).ToString());
Console.WriteLine(typeof(A).IsSubclassOf(typeof(Interface2)).ToString());
Console.ReadLine();
}


Both return False. Given a type what is the simplest way of checking if it
implements Interface1 either directly, or by implementing Interface2?
 
C

Christopher Ireland

Peter said:
Both return False. Given a type what is the simplest way of checking
if it implements Interface1 either directly, or by implementing
Interface2?

How about GetInterface(), e.g.

static void Main(string[] args)
{
Console.WriteLine(typeof(A).GetInterface("Interface1").Name ==
typeof(Interface1).Name);
Console.ReadLine();
}
 
P

Peter Morris

Console.WriteLine(typeof(A).IsAssignableFrom(typeof(Interface1)).ToString());
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(Interface2)).ToString());
Console.ReadLine();

OUTPUT:
False
False

Any other ideas?
 
P

Peter Morris

Obvious when you know how!

typeof(IInterface1).IsAssignableFrom(typeof(A));

If A implements IInterface1 then it means A can be assigned to IInterface1,
not that IInterface1 can be assigned to A!
 
B

Ben Voigt [C++ MVP]

Peter said:
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(Interface1)).ToString());
Console.WriteLine(typeof(A).IsAssignableFrom(typeof(Interface2)).ToString());
Console.ReadLine();
OUTPUT:
False
False

Any other ideas?

Turn the logic around, the interface is assignable from the class (upcast)
but the reverse (downcast) is not true.
 

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