1

I want to call FamilyCar method Move(). If FamilyCar is a LandVehicle, I want to call LandVehicle Move() method at the same time. I'm looking for very basic way to do it.

Base class

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }

Subclass

class FamilyCar : LandVehicle
{
        public override string Move()
        {
            return "Pip pip!";
        }
}
h0ax
  • 51
  • 6
  • “If FamilyCar is a LandVehicle...” What do you mean? A FamilyCar is always a LandVehicle. – Sweeper Jul 15 '20 at 10:20
  • True, the fact is that I have more subclasses except FamilyCar. For each LandVehicle i want method Move() from LandVehicle to call and additionaly call their own method called the same that is more specified. – h0ax Jul 15 '20 at 10:25
  • Did you mean "If LandVehicle is a FamilyCar..."? And what would the method return? Would it return what `LandVehicle.Move` returns or would it return what `FamilyCar.Move` returns? It can't return both. – Sweeper Jul 15 '20 at 10:27
  • 3
    do you mean how to call base method in derived class like `base.Move()` in `FamilyCar.Move()`? – Selvin Jul 15 '20 at 10:28
  • 3
    You can use `base.Move()` to call the parent's `move` function. Of course you can't `return` twice so you have to refactor that part. – Kokodoko Jul 15 '20 at 10:29
  • Thanks a lot, that what i was looking for. base.Move() Ty guys! – h0ax Jul 15 '20 at 10:32
  • 2
    @h0ax That is part of polymorphism mechanisms, and here, calling the base class as you ask for: [What is polymorphism](https://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used/58197730#58197730). I hope this can help you to enjoy C# coding: [How do I improve my knowledge in C#](http://www.ordisoftware.com/files/stack-overflow/CsharpBegin.htm). –  Jul 15 '20 at 10:37
  • Why this unclear, dup question has +2 ? – Selvin Jul 15 '20 at 10:39

1 Answers1

5

You can use base.Move() to call the parent class Move method:

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }

Subclass

class FamilyCar : LandVehicle
{
        public override string Move()
        {
            base.Move(); //this will call LandVehicle.Move()
            return "Pip pip!";
        }
}
Aman B
  • 2,276
  • 1
  • 18
  • 26