Inheritence (iteration)

  • Thread starter Thread starter csharpula csharp
  • Start date Start date
C

csharpula csharp

Hello,

I have 3 classes: classA,classB,classC. B and C inherit from A.

I want to prefer the following operation on a list of classA objects
(which can be from type classA,classB or classC) - let's refer to it as
listA.

foreach (classB bObjects in listA)
{
}
Is that possible to fetch only the B objects from the general list?

Thanks!
 
It is very simple with .NET 3.5 and C# 3.0 - just use

foreach (classB bObjects in listA.OfType<classB >())
{
// ...
}

If you can't use this option, then just use "as" to check:

foreach (classA tmp in listA)
{
classB obj = tmp as classB;
if(obj == null) continue;

// ...
}

Marc
 
I don't using the last framework,so is it a must to do the check you did
if the object is not null?
 
Yes... the null check is how you exclude objects that aren't (at least)
classB.

Marc
 
Back
Top