471,344 Members | 1,452 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,344 software developers and data experts.

C# Reflection and 'is' operator

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
Jul 21 '05 #1
3 1757
Tooc wrote:
if(shape.GetType() == type) // compiles OK
but this doesn't give the answer I want when I pass an interface type.

Use the Type.IsAssignableFrom method.

if(shape.GetType().IsAssignableFrom(type))

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Jul 21 '05 #2
Thanks for the nudge.

Actually it's the other way round

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

"Anders Norås" <an**********@objectware.no> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
Tooc wrote:
if(shape.GetType() == type) // compiles OK
but this doesn't give the answer I want when I pass an interface type.

Use the Type.IsAssignableFrom method.

if(shape.GetType().IsAssignableFrom(type))

Anders Norås
http://dotnetjunkies.com/weblog/anoras/

Jul 21 '05 #3
Tooc wrote:
Actually it's the other way round

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


Sorry. Mozilla Thunderbird is a great newsreader, but its a lousy
development environment. :) I mixed up the order.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Jul 21 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by JMZ | last post: by
5 posts views Thread by Digital Fart | last post: by
reply views Thread by Ronak mishra | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.