Saturday, July 07, 2007

What is Virtual Method in .Net?

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:

Imran said...

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 [:)]

DotNetGuts said...

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

Parag said...

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

Anonymous said...

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

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape