Pages

Wednesday, May 15, 2013

pure vartual function in c#

A pure virtual function makes the class an abstract class, which itself cannot be instantiated. This means that to use the class, you have to inherit from it, and you MUST override all pure virtual functions defined in the abstract class
-> In c# abstract function are treated as pure virtual funcion.
->We can't use the virtual modifier with the static, abstract, private or override modifiers

   Note: 

 When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class

How declare a pure virtual function in C#:

1. Firstly, the class must always be declared abstract.
2.Secondly, the method must be declared abstract.

Sample code:

 public abstract class L
  {
   public int x=10; // not abstract/virtual method
    public abstract int m();
  }
public class N:L
  {
    public override int m()
     {
      return 100;
     }
     public int x=20;
  }
public class Test
  {
   protected void page_load(-,-)
    {
    N n=new N();
    int r=n.m();
    Response.write(r); //100 
    Response.write(n.x); //20
    L l1=n;  //downcast
    int r2=l1.m();
    Response.write(r2); //100
    Response.write(l1.x); //10
       
    
     

No comments:

Post a Comment