Search code examples
c#.netoopoverridingvirtual

virtual keyword in c#


I have knowledge of Java and have been learning C# for the last couple of days. Now I have come across the "virtual" keyword which, as suggested at this link, is used to allow the corresponding methods, properties etc. to be overriden in the subclasses. Now I think we can override methods even without using the "virtual" keyword. Then why it is necessary?


Solution

  • You need the virtual keyword if you really want to override methods in sub classes. Otherwise the base implementation will be hidden by the new implementation, just as if you had declared it with the new keyword.

    Hiding the methods by "overriding" them without the base method being declared virtual leaves you without polymorphism, that means: if you "cast" a specialized version to the "base" version and call a method, always the base classes implementation will be used instead of the overridden version - which is not what you'd expect.

    Example:

    class A
    {
        public void Show() { Console.WriteLine("A"); }
    }
    
    class B : A
    {
        public void Show() { Console.WriteLine("B"); }
    }
    
    A a = new A();
    B b = new B();
    
    a.Show(); // "A"
    b.Show(); // "B"
    
    A a1 = b;
    a1.Show(); // "A"!!!