Search code examples
c#language-features

how can we override method in child class without using "virtual" in parent class


This is a interview question. So is it possible to override a method without virtual specified in parent method?


Solution

  • They probably wanted you to say "Use the new keyword to hide the method." Which technically does not override the method. If you have

    class Base
    {
        public void Bar() { Console.WriteLine("Base"); }
    }
    
    class Derived : Base
    {
        public new void Bar() { Console.WriteLine("Derived"); }
    }
    

    And then you wrote

    Derived derived = new Derived();
    derived.Bar();
    ((Base)derived).Bar();
    

    You would see different results. So functions that use the base class would get the results for the base method, and functions that use the derived class would get the results for the new method.