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
    }
}
                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
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With