user3533030
user3533030

Reputation: 449

C# / accessing methods of sub-classes in a list when accessing through foreach

Trying to understand how to access the methods of a sub-class when the list is typed as the superclass. This should be basic polymorphism, but I'm getting confused.

public class super
{ 
  public Boolean isSuper()
  {
    return true;
  }
}

public class sub : super
{ 
  public Boolean isSuper()
  {
    return false;
  }
}

Now I make a list of these objects

List <super> myList = new List<super>();
myList.Add(new super());
myList.Add(new sub());

Now I try to get each object in the list to query itself to see if it is a super-class or a sub-class

foreach(super objInList in myList)
{
  if(objInList.isSuper())
    Debug.Print("Super");
  else
    Debug.Print("Sub");
}

So what happens is that since each object is cast as a super-class, it uses the super-class method of isSuper() and it always responds as a super-class.

I want to access the sub-classes' isSuper() without having to use an instanceof in every single iteration of the loop. Obviously if you can query the object to see if it is a super or a sub, then something in the O/S knows the type of object. Why go through a guessing game of checking each possibility? Why not ask it to drill down to the appropriate sub-class and execute the appropriate method? Is there a way to achieve this goal?

Upvotes: 1

Views: 283

Answers (1)

st4hoo
st4hoo

Reputation: 2204

You have to override super class property in your sub class to get required behaviuor.

Change your class definitions accordingly:

public class super
{ 
  public virtual Boolean isSuper()
  {
    return true;
  }
}

public class sub : super
{ 
  public override Boolean isSuper()
  {
    return false;
  }
}

Upvotes: 9

Related Questions