2

I have:

class A class B : A class C : B class D : B

And I have a List

Where actual objects of C and D are stored.

How can I check whether the objects in List is a subtype of B?

Currently, I'm doing item.GetType() == typeof(C) || item.GetType() == typeof(D)

This works, but what if I had more than 2 classes that are inherited from B? Writing all of them down seems redundant. Is there a way to check whether the object is a subtype of B? Thanks!

JASON
  • 7,371
  • 9
  • 27
  • 40
  • http://stackoverflow.com/questions/2742276/in-c-how-do-i-check-if-a-type-is-a-subtype-or-the-type-of-an-object – qxg May 14 '14 at 06:45

2 Answers2

6

You can use the is keyword.

if(item is B)

Reference: http://msdn.microsoft.com/en-us/library/scekt9xw.aspx

Bhushan Shah
  • 1,028
  • 8
  • 20
1

Have you considered using casts? Check this out if you dont know what it is

In case of cast operations that involve base and derived types, there is a risk of throwing exceptions. To test for compatibility before actually performing a cast, C# has provided two operators to allow casting safely without causing any exceptions. The two operators are:

The ‘Is’ operator used to check for successful casting from one reference type to another and to determine an object ‘s type without casting it.
The ‘As’ operator used to obtain the cast value, if the cast can be made successfully and hence more efficient.

Victor
  • 907
  • 2
  • 17
  • 42