Pages

Men

rh

7/01/2012

Virtual Function in C#

Virtual Function:
They implement the concept of polymorphism; are the same as in C#, except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.


Why to use them:
  •  It is not compulsory to mark the derived/child class function with override keyword while base/parent class contains a virtual method
  • Virtual methods allow subclasses to provide their own implementation of that method using the override keyword
  •  Virtual methods can't be declared as private.
  •  You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method
  •  A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
  • We will get a warning if we won't use Virtual/New keyword.
  •  Instead of Virtual we can use New Keyword
Example:
class A
{
public void M()
{
Console.WriteLine("A.M() being called");
}

public virtual void N()
{
Console.WriteLine("A.N() being called");
}
}

class B : A
{
public new void M()
{
Console.WriteLine("B.M() being called");
}

public override void N()
{
Console.WriteLine("B.N() being called");
}
}

say

A a = new B();

a.M();
a.N();

The results would be

A.M() being called
B.N() being called

No comments :

Post a Comment