What is Virtual Method in .Net?
By declaring base class function as virtual, we allow the function to be overridden in any of derived class.
Example of Virtual Method in .Net:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.
4 comments:
Virtual does not means only for overridden. Its for special purpose call Runtime Polymorphism.
This means at rume time compiler decide which methed will get called based on the pointer.
In your example the reason while hello of child called just because of pointer is of child class and the method is virtual.
We can override any method of parent with out virtual, its all of inheritance fundas [:)]
Thanks Imran for your valuable comment, well its not possible to display each and every permutation and combination of funda, but i have tried to explain the most basic funda wherein anyone can master the funda:)
Keep Going Good Work,
Cheers,
DotNetGuts (DNG)
http://dotnetguts.blogspot.com
If i have a virtual method declared in base class and i am not using it anywhere in my application then ,what will happen ?
PARAG
Hi Parag,
If you are not using the Virtual class any where in your application, the compiler will not execute the virtual method assuming the derived class will overrides that, so it will skip the method the moment it sees the virtual method.
Regards,
Fahad Ahmed Khan
fahadmca2004@gmail.com
Hyderabad, (AP)INDIA
Post a Comment