Inheritence (iteration)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • csharpula csharp

    Inheritence (iteration)


    Hello,

    I have 3 classes: classA,classB,c lassC. 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!







    *** Sent via Developersdex http://www.developersdex.com ***
  • Marc Gravell

    #2
    Re: Inheritence (iteration)

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

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

    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

    Comment

    • csharpula csharp

      #3
      Re: Inheritence (iteration)


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


      *** Sent via Developersdex http://www.developersdex.com ***

      Comment

      • Marc Gravell

        #4
        Re: Inheritence (iteration)

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

        Marc

        Comment

        Working...