0

I have a question about the casting from Base to get Derive Class method. Here is my code:

class Vehicles
{
    public void SpecificRequiredTask()
    {
        Console.WriteLine("Base method");
    }
}

class Cars : Vehicles
{
    public new void SpecificRequiredTask()
    {
        Console.WriteLine("Derive method");
    }
}

class Program
{
    Vehicles car = new Cars();
    //I want to call the derive method, not base method, so that I do the 
    //casting
    ((Cars)car).SpecificRequiredTask();
}

The problem is my professor said that "This is not required because you already have an object of type Cars." But I know that without the casting (Cars), the program will still call the method from Base class.

Please help me to correct my understanding if it's incorrect. Thank you

DanielQ
  • 1
  • 1
  • There is a language feature for that... https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual – Timbo Oct 01 '17 at 20:20
  • Hey Timbo, thanks for comment, I just checked, and I did exactly the same, I just don't use virtual & override, I used overloading instead so still wonder if my solution is incorrect or it's not a valid casting. – DanielQ Oct 01 '17 at 20:28
  • 1
    I strongly suspect the point of the exercise *is* to use `virtual` and `override`. – Jon Skeet Oct 01 '17 at 20:40
  • @DanielQ congrats on having Jon Skeet answering to your question. That might actually impress your prof more than the correct usage of `virtual` and `override` (which you should use). – Waescher Oct 01 '17 at 20:43
  • Hi all, thanks for your suggestion, I would definitely use [virtual] and [override] next time. But just a confirmation that did I do something wrong with the code above? – DanielQ Oct 01 '17 at 20:47
  • *"did I do something wrong with the code above?"* If the point is to use overriding *as Jon suggested*, then yes, you probably did. Check [this answer](https://stackoverflow.com/a/3838692/4934172) which has a very similar example to yours. – 41686d6564 stands w. Palestine Oct 01 '17 at 21:02

0 Answers0