views:

251

answers:

3

An easy question I guess, but in the documentation of the Type class they only talk of interfaces on the GetInterfaces method.

i.e. typeof(ChildClass).XXX(typeof(ParentClass)

+11  A: 

It depends on what you need; IsAssignableFrom, perhaps:

bool stringIsObj = typeof(object).IsAssignableFrom(typeof(string));

or IsSubclassOf:

bool stringIsObj = typeof(string).IsSubclassOf(typeof(object));
Marc Gravell
do you know what the diference is?
Hugo
Sure; interfaces will work differently (they won't be subclasses) - and Foo will be assignable from Foo, but Foo isn't a subclass of Foo (IsSubclassOf is a **strict** subclass)
Marc Gravell
For example, this is true: bool stringIsComparable = typeof(IComparable).IsAssignableFrom(typeof(string));
Marc Gravell
Marc - Out of curiosity, how do you monitor for new questions that you answer? :)
shahkalpesh
Marc - Also, how do you monitor comments to your answer?
shahkalpesh
Answer to both... I simply pop in occasionally; sometimes there is something to do; sometimes there isn't...
Marc Gravell
Comments to your answers show up in the envelope icon.
Joel Coehoorn
+2  A: 

typeof(ParentClass).IsAssignableFrom(typeof(ChildClass))

ckarras
+1  A: 

I suggest you search for an equivalent. Instead of using the "is" keyword like this:

if (object is class)
{ ... }

you could simply compare the types of those two like this:

if( typeof(object) == typeof(class)
{ ... }

BUT: this is not the same, the "is" keyword can determine if the object-class is of the specified class, an inheritence of that class, implements the interface, etc, whereas the typeof() equivalence just compares the actual type.

BeowulfOF
See http://stackoverflow.com/questions/1185559/in-c-what-is-the-equivalent-of-is-keyword-but-using-type-objects/1185570#1185570.
John Saunders