Inheritence (iteration)

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!
 
M

Marc Gravell

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
 
C

csharpula csharp

I don't using the last framework,so is it a must to do the check you did
if the object is not null?
 
M

Marc Gravell

Yes... the null check is how you exclude objects that aren't (at least)
classB.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top