GetInterface() without a string

  • Thread starter Thread starter Gomaw Beoyr
  • Start date Start date
G

Gomaw Beoyr

If I have an object o and want to check if it's a certain interface,
I write like this:

bool oIsIMyInterface = o is IMyInterface;

However, if I have a Type object t, and I want to check if it's a
certain interface, I have to write the interface name as a string:

bool tIsIMyInterface = t.GetInterface("MyNamespace.IMyInterface") != null;

Is there any way to do this without putting the interface between
quotes, i.e. without writing it as a string, i.e. getting it
type-checked etc by the compiler?

Something along these lines:

bool tIsIMyInterface = t.IsSubclassOf(typeof(IMyInterface)) != null;


Regards,
/Gomaw
 
Hey,

you can do this with the object itself. When you have an object o which
implements an interface i,
"o is i" will return true. So you can write: if(o is i) { // o implements
the interface i}
For further info lookup the is ( and as) operators.

Greetz,
-- Rob.
 
Gomaw Beoyr said:
If I have an object o and want to check if it's a certain interface,
I write like this:

bool oIsIMyInterface = o is IMyInterface;

However, if I have a Type object t, and I want to check if it's a
certain interface, I have to write the interface name as a string:

bool tIsIMyInterface = t.GetInterface("MyNamespace.IMyInterface") != null;

Is there any way to do this without putting the interface between
quotes, i.e. without writing it as a string, i.e. getting it
type-checked etc by the compiler?

Something along these lines:

bool tIsIMyInterface = t.IsSubclassOf(typeof(IMyInterface)) != null;

Check out System.Type.IsAssignableFrom().
 
you can do this with the object itself. When you have an object o which
implements an interface i,
"o is i" will return true. So you can write: if(o is i) { // o implements
the interface i}

Yes, thanks, but my problem was that I don't have an object. The
program checks if the class (represented by a Type object) implements
the interface, and if it does, an object is instantiated with
Activator.CreateInstance().

The way to solve the problem was posted by Mike Schilling, where t
is the Type object:

bool tIsIMyInterface = typeof(IMyInterface).IsAssignableFrom(t);

(I assume that the only way an interface can be assignable from a
type is if the type implements the interface...)

Gomaw
 
Back
Top