How to tell if an object implements an interface. ???

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

I need to be able to do a check on an object to tell IF it inherits a given
interface.

There has to be a way to do this, but haven't found it anywhere.

Please help, Mark
 
all you have to do to is:
class MyClass:IMyInterface{
}

object x = new MyClass()
if(x is IMyInteface){
...your logic if x implements IMyInteface
}
Hope this helps!
 
Can i use

if(X is MyClass)

even if MyClass is a class not an interface ?

What is the différence between this and that :
if(x.GetType() == typeof(MyClass)) ??

thanks
ROM
 
I think that is is just a c# compiler keyword. Compiler probably does that
during compilation, but i am not sure.
 
Romain TAILLANDIER said:
Can i use

if(X is MyClass)

even if MyClass is a class not an interface ?

Yes you can.
What is the différence between this and that :
if(x.GetType() == typeof(MyClass)) ??

Speed (is is much faster) and precision. For instance:

object x = "hello";

x is object: true
x.GetType() == typeof(object): false

Using == on the Types involved, the types have to match exactly. Using
"is" (or Type.IsAssignableFrom) checks the hierarchy.
 
GRAAAAA

Thank you Jon !
and thank you mark vlad and mike to discuss about that ...

I didn't know about the 'is', and i just look for it in MSDN ....
So i discover the 'as' too
before i was using if elseif elseif ... else structure to determine exact
type of my custom controls, because i wasn't able to test if these controls
was corresponding to the interface of all this controls.
I will now be able to simplify lot of code ...

Thanks you all
ROM





"Jon Skeet [C# MVP]" <[email protected]> a écrit dans le message de (e-mail address removed)...
Romain TAILLANDIER said:
Can i use

if(X is MyClass)

even if MyClass is a class not an interface ?

Yes you can.
What is the différence between this and that :
if(x.GetType() == typeof(MyClass)) ??

Speed (is is much faster) and precision. For instance:

object x = "hello";

x is object: true
x.GetType() == typeof(object): false

Using == on the Types involved, the types have to match exactly. Using
"is" (or Type.IsAssignableFrom) checks the hierarchy.
 
Back
Top