Tuesday, March 19, 2013

Method Overriding in C#.net


Method Overriding in C#.net with example

LoadParent:
public void Test() -> 1
public virtual void Test(int x)

LoadChild:
public void Test(string s) -> 3
public override void Test(int x) -> 4
public void PTest(int x) -> 2

-After Overriding a method under the Child Class can we also consume the parent's method from the Child ?

Ans: Yes this can be done in 2 ways:
   1. Create the object of the parent under the child class and then call the virtual method of the Parent.
   -To test this re-write the following code under the Main method of the class LoadChild.
            LoadParent P = new LoadParent();
            P.Test(10);   //Calls Parent Method
            LoadChild c = new LoadChild();
            c.Test(10);   //Calls Child Method

Note: If the object of the child class was assigned to the parents variable and then if we invoke the overridden method, parent object also will invoke child methods only, as it has given the permission for the child to override the method it will give the preference to child methods.

-To test this re-write the following code under the Main method of the class LoadChild.
            LoadChild c = new LoadChild();
            LoadParent p = c;
            p.Test(10);   //Calls Child Method
            c.Test(10);   //Calls Child Method

   2. Using the base keyword also we can call the virtual methods of the parent from the child class.
Note: using the base keyword is not allowed from static blocks like Main.

-To test this do the following:
   i) Add a new method under the child class LoadChild as PTest which will internally call the virtual method of the parent.
  public void PTest(int x)
{
    base.Test(x);
}
   ii) Now from the Main method of the child class LoadChild u can call all the methods by using the object of the child class only as following:
LoadChild c = new LoadChild();
c.Test();              //Calls Parent Method
  c.PTest(10);       //Calls Parent Method
c.Test("Hello");  //Calls Child Method
c.Test(10);         //Calls Child Method

No comments:

Post a Comment

amazon

Sukanya Samriddhi Account - SBI

SUKANYA SAMRIDDHI Account information by SBI SUKANYA SAMRIDDHI ACCOUNT : FACILITY AVAILABLE AT ALL BRANCHES OF SBI Sukanya Samriddhi ...