views:

36

answers:

2

I have a super-class named "ClassA" and two sub-classes "Class1" and "Class2".

I have a list containing objects of "Class1" and "Class2", that list is of type "ClassA".
I want to loop through only the "Class1" objects in the list by doing something like

List<ClassA> AList = new List<ClassA>;
AList.Add(new Class1());
AList.Add(new Class2());

foreach (Class1 c1 in AList)
{
    // Do Something
}

but when I do that, the code throws an exception when it reaches an object that is not of type "Class1".

How can this be done in a simple way without having to check the type of the object in the list and cast it if it's the correct type. like this:

foreach (ClassA cA in AList)
{
    if (cA.GetType() == typeof(Class1))
    {
        // Do Something
    }
}
+3  A: 

Using LINQ:

foreach (Class1 c1 in AList.OfType<Class1>()) { }

Note that if you want to check for a type in a loop, the as and is operators are meant for this. Like:

foreach (ClassA cA in AList) {
  Class1 c1 = cA as Class1;
  if (c1 != null) {
    // do something
  }
}
Julien Lebosquain
I have to use .NET 2.0 and can't use LINQ
Amr
Use the "as" option then.
Mohamed Meligy
+1  A: 
foreach(Class1 c1 in AList.OfType<Class1>())
{
    //do something
}
Lee
I have to use .NET 2.0 and can't use LINQ
Amr