Write a code snippet that implements Virtual keyword ,overrides the virtual method in C#.

 Posted by Nagasundar_Tn on 11/29/2012 | Category: C# Interview questions | Views: 2814 | Points: 40
Answer:

A virtual method can be redefined.The virtual keyword is used to modify a method and allow it to be overridden in a derived class. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.

Here is the code snippet :

class Base

{
public virtual void FncOverride()
{
Console.WriteLine("Base Override");
}
}

class Derived : Base
{
public override void FncOverride()
{
Console.WriteLine("Derived Override");
}
}
class Program : Derived
{
static void Main(string[] args)
{
// Compile-time type is Base.
// Runtime type is also Base.
Base bObj = new Base();
bObj.FncOverride();

// Compile-time type is Base
// Runtime type is Derived.
Base bdObj = new Derived();
bdObj.FncOverride();
}
}


In the above code the base class has FncOverride() method with Virtual keyword and overriding that method in Derived class. In my Main() function I am calling the base class FncOverride() method in following way
     Base bObj = new Base();

bObj.FncOverride();

Now the calling function will be known to compiler at compile time itself.
But when accessing the method like this:
  Base bdObj = new Derived();

bdObj.FncOverride();

This time the derived class function will be called. And the compiler decides at run time that which method should be invoked.

While executing the above code we get
Base Override

Derived Override


Asked In: SRA Systems | Alert Moderator 

Comments or Responses

Login to post response