Yachit Kumar
What is Virtual Method in C#?
Posted by Yachit Kumar in C# Language on Nov 04, 2012
  • 0
  • 2
  • 1076
Do you know the answer for this question? Post it below.
Guest
Posted by dinesh maurya on Nov 16, 2012
  • 0

A virtual method can be redefined. In the C# language, the virtual keyword designates a method that can be overridden in derived classes. This enables you to add new, derived types without modifying the rest of your program. The runtime type of objects thus determines what your program does.
Keywords
Example
Note

This program introduces two classes, A and B. Class A has a public virtual method called Test. Class B, meanwhile, derives from class A and it provides a public override method called Test as well.

The virtual modifier tells the compiler that when any class derived from class A (such as class B) is used, an override method should be used instead of the virtual method.
Override Method

Program that introduces virtual method [C#]

using System;

class A
{
public virtual void Test()
{
Console.WriteLine("A.Test");
}
}

class B : A
{
public override void Test()
{
Console.WriteLine("B.Test");
}
}

class Program
{
static void Main()
{
// Compile-time type is A.
// Runtime type is A as well.
A ref1 = new A();
ref1.Test();

// Compile-time type is A.
// Runtime type is B.
A ref2 = new B();
ref2.Test();
}
}

Output

A.Test
B.Test

Posted by Yogesh Sharma on Nov 09, 2012
  • 0

The virtual modifier tells the compiler that when any class derived from class A (such as class B) is used, an override method should be used instead of the virtual method.


Most Popular Companies

Most Popular Job Functions

MOST LIKED QUESTIONS

PRIVACY POLICY | TERMS & CONDITIONS | SITEMAP | CONTACT US | ABOUT US | REPORT ABUSE
2014© C# Corner. All contents are copyright of their authors.