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!"; } } 
8
  • “If FamilyCar is a LandVehicle...” What do you mean? A FamilyCar is always a LandVehicle. Commented Jul 15, 2020 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. Commented Jul 15, 2020 at 10:25
  • 3
    do you mean how to call base method in derived class like base.Move() in FamilyCar.Move()? Commented Jul 15, 2020 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. Commented Jul 15, 2020 at 10:29
  • 2
    @h0ax That is part of polymorphism mechanisms, and here, calling the base class as you ask for: What is polymorphism. I hope this can help you to enjoy C# coding: How do I improve my knowledge in C#. Commented Jul 15, 2020 at 10:37

1 Answer 1

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!"; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Will call but does nothing with the result ...
@Selvin that's true but I think OP just wanted to know how to call the base class method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.