C# 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
 
Thanks for the nudge.

Actually it's the other way round

if(type.IsAssignableFrom(shape.GetType())) count++;
 
Back
Top