Search code examples
c#.netoopinheritancevirtual

Why do I need to declare a Virtual Method when I can Hide it in derived Class


class clsTestParent
    {
       public void testNoAbstract()
        {
            Console.WriteLine("Parent Method Call");
        }
    }

    class clsDerivedTest : clsTestParent
    {
     public void testNoAbstract()
        {
            Console.WriteLine("Child Method Hiding Parent Method");
        }
    }

            clsTestParent objParent = new clsTestParent();
            clsTestParent objOfParentFromDerived = new clsDerivedTest();
            clsDerivedTest objDerived = new clsDerivedTest();

            objParent.testNoAbstract();
            objOfParentFromDerived.testNoAbstract();
            objDerived.testNoAbstract();

Output:
Parent Method Call
Parent Method Call
Child Method Hiding Parent Method

But when I declare testNoAbstract() as virtual and over ride in derived class , then the out put will be as below:

Parent Method Call  
Child Method Hiding Parent Method
Child Method Hiding Parent Method

Earlier I used to think , we can only redefine a method in derived class , if that is defined as abstract or virtual , but as can see now , we can hide the parent class method just by redefining it in derived class.

Though , I can see , the difference in output by changing the code , I would like to know , What are the differences between above two methods and why it yields different out put.


Solution

  • If youll ever do clsTestParent a = new clsDerivedTest () - you'll never be able to execute the one in the clsDerivedTest class !!!!

    Thats the difference and thats why the compiler warns you.

    you'll actually gonna do that if you wish to preform a Polymorphism architecture.

    Microsoft tells you : " listen , you direved a class , and we will give you all the public things etc but we dont know how do you want to implement the methods ... if you'll use the virtual + override - youll be able to execute a different method via the instace type. and if you wont override - so the function of the father will always be executed.... its your choice ... we are warning you "... and they do warn