Pages

Monday, May 13, 2013

virtual and override in c#

Virtual:

A virtual metod is a method whose behaviour we can change in the derived class
 ->In c# virtual method ,virtual properties,virtual
->In case virtual method ,constructor not supported in c#
-> Here signature will not be change

Overriding:

Sometimes we might requred to change the behaviour of base class member in the derived class which is refered as overridding.
->In order to change the behaviour of a base class member in the derived class, base class member must be declared as a vartual method and derived class method should be  declared with keyword

Note:suppose you develop a software after few month/year you need to change the code,that time if u not write virtual method not possable to change,its better to use virtual and override method

Sample code:

public partial class program1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        B b = new B();
        int r1 = b.m(10,20);
        Response.Write(r1);
        A a = b; //downcasting
        int r2 = a.m(10, 20);
        Response.Write(r2);
   }
}
public class A
{
   public virtual int m(int x,int y)
   {
       int z=x+y;
       return z;
   }
}
public class B:A
{
    public override int m(int x,int y)
       {
          int z=x-y;
         return z;
       }
}

Note:

-> overridding best example Dynamic polymorphisim
-> By using vartual and override method we can achive polomerphisim
->In case of over loading method signature and return type should be same.

Sample code:  ????????? 

{
 C c1=new C();
B b1=c1;
A aa=b1;  // or c1;
int r1=c1.m(10,20);
int r2=b1.m(10,5);
int r3=a1.m(10,5);
Response.Write(r1+"<br/>"+r2+"<br/>"+r3+"<br/>");
Public class A
{
   public vartual int m(int x,int y)
      {
         return x+y;
       }
 }
public class B:A
  {
    public override int m(int a,int b)
    {
      return a-b;
     }
}
public class C:B
  {
   Public override int m(int x,int y)
    {
       return 2*(x-y);
     }
}
Note: output will be come like(?)


 

 

 

No comments:

Post a Comment