implement

J

J-L

HI,

I don't find the method ro detect if a class implement an interface.

I try

if (MyObject implements MyInterface)

but it doesn't work.

if (MyObject is MyInterface)

work. Is it the only method to do that ?

J-L
 
H

Hans Kesting

J-L submitted this idea :
HI,

I don't find the method ro detect if a class implement an interface.

I try

if (MyObject implements MyInterface)

but it doesn't work.

if (MyObject is MyInterface)

work. Is it the only method to do that ?

J-L

the "is" operator works with both interfaces and (base)classes.
Basically it's "can I treat 'MyObject' as a 'MyInterface'".

A different way would be the "as" operator, which tries a cast but
gives a 'null' if it didn't work:
MyInterface mi = MyObject as MyInterface;
if (mi != null) ...

And if you really want to, you could also use reflection.

Hans Kesting
 
M

Michael Nemtsev [MVP]

Hello J-L,

Use

if (typeof(MyInterface).IsAssignableFrom(MyObjectType))

or

if (MyObjectType.GetInterface(typeof(MyInterface).FullName)


---
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo


J> HI,
J>
J> I don't find the method ro detect if a class implement an interface.
J>
J> I try
J>
J> if (MyObject implements MyInterface)
J>
J> but it doesn't work.
J>
J> if (MyObject is MyInterface)
J>
J> work. Is it the only method to do that ?
J>
J> J-L
J>
 
J

J-L

the "is" operator works with both interfaces and (base)classes. Basically
it's "can I treat 'MyObject' as a 'MyInterface'".

A different way would be the "as" operator, which tries a cast but gives a
'null' if it didn't work:
MyInterface mi = MyObject as MyInterface;
if (mi != null) ...


Thanks a lot !
 

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