0

Considering the knowledge I learned, this value should definitely be printed on a value of 20 instead of 10. But why does 10 come out? Am I misunderstanding the concept of override?

class Parent
{
    public int Question()
    {
        return 10;
    }
}

class Child : Parent
{
    public new int Question()
    {
        return 20;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Parent parent = new Child();
        Console.WriteLine(parent.Question());
    }
}
helpme
  • 1
  • 2
    You're not overriding. You're using `new`, which explicitly *doesn't* override. Use `virtual` in `Parent`, and `override` in `Child` – canton7 Apr 16 '21 at 14:06
  • You're not overriding, you're hiding, you need to use `virtual`/`override` instead of `new`. – Alejandro Apr 16 '21 at 14:06
  • 1
    Does this answer your question? [Difference between shadowing and overriding in C#?](https://stackoverflow.com/questions/392721/difference-between-shadowing-and-overriding-in-c) – pmcoltrane Apr 16 '21 at 14:07
  • using `public new int ...` **doesn't** override. If you need/ want to override the base method, make the base method `virtual int ...` and the method that overrides it `override int ...` – MindSwipe Apr 16 '21 at 14:07

0 Answers0