Buksy
Buksy

Reputation: 12218

Call overriden method from base class

Is there a way to call overriden method from the base class?

class SpaceObject {
  public draw() {}
}
class Sun : SpaceObject{
  public draw() {}
}

Sun planet1 = new Sun();
SpaceObject planet2 = new SpaceObject();
SpaceObject planet3 = new SpaceObject();

List<SpaceObject> objs = new List<SpaceObject>();
objs.Add(planet1);
objs.Add(planet2);
objs.Add(planet3);

foreach(SpaceObject o in objs)
  o.draw();

Is there a way so that in foreach for planet1 there will be call on Sun::Draw() instead of SpaceObject::Draw() ?

Right now I have it this way

foreach(SpaceObject o in objs)
  if(o.GetType() == typeof(Sun) ((Sun)o).draw();
  else o.draw();

But I plan to have multiple inheritances of SpaceObject so this is not a good way to go.

Upvotes: 0

Views: 117

Answers (2)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

Change your SpaceObject and Sun class this way

    class SpaceObject
    {
        public virtual void draw()
        {
            Console.WriteLine("Log from parent");
        }
    }

    class Sun : SpaceObject
    {
        public override void draw()
        {
            Console.WriteLine("Log from Child");
        }
    }

And you do not need the if checking and type casting. Just call

o.draw();

Upvotes: 3

Voidpaw
Voidpaw

Reputation: 920

Make the SpaceObject.Draw() method virtual, that way you can give the Sun an override Draw() method. For more info you might want to look at This link on the Microsoft pages to learn more about the topic of inheritance.

Upvotes: 5

Related Questions