Reflection and 'is' operator

  • Thread starter Thread starter Tooc
  • Start date Start date
T

Tooc

I am trying to pass the type of an object to a method, and then check object
references against it to see if they are of that type, using the C# operator
is.

However, my syntax is wrong - see below.

// Main
{
....
CountByType(typeof(Circle));
CountByType(typeof(IStraightSided));
....
}

static int CountByType(Type type)
{
int count = 0;
foreach(Shape shape in shapes)
{
if(shape is type) // incorrect syntax
count++;
}
return count;
}

I have tried
if(shape.GetType() == type) // compiles OK
but this doesn't give the answer I want when I pass an interface type.

I am looking for an elegant solution to this if possible. Failing that I'll
settle for the least inelegant!

I am now in deep philosophy mode about why the is operator seems only to
work with the explicit type name - maybe it is a compile-time thing. The
..NET help doesn't actually state this, however.

Annoying, eh?

tooc
 
Try if(shape.GetType().Equals(type))

This will work if "shape" is of type "type". If you want to check for
subclasses of "type", you can use (shape.GetType().IsSubClassOf(type))

Hope this helps.

Cheers
Jako
 
Tooc said:
I am trying to pass the type of an object to a method, and then check
object
references against it to see if they are of that type, using the C#
operator
is.
Try

static int CountByType(Type type)
{
int count = 0;
foreach(Shape shape in shapes)
{
if(type.IsAssignableFrom(typeof(shape)))
count++;
}
return count;
}

David
 
I believe you want something like
type.IsAssignableFrom(shape.GetType())

Or maybe I have that backwards?
-Rachel
 
Back
Top