What do you mean by virtual property? Give an example?

 Posted by Tripati_tutu on 11/15/2010 | Category: C# Interview questions | Views: 2727 | Points: 40
Answer:

A property declared with virtual keyword is considered as virtual property. These enables derived classes to override the property behavior by using the override keyword. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

class Employee
{
private string fName = string.Empty;
Private string lName = string.Empty;

public string FirstName
{
get
{
return fName;
}
set
{
fName = value;
}
}

public string LastName
{
get
{
return lName;
}
set
{
lName = value;
}
}
// Here take FullName is as a virtual
public virtual string FullName
{
get
{
return fName + ", " + lName;
}
}
}

class Company : Employee
{
// Overiding the FullName virtual property derived from employee class
Public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}

class Main
{
public static void Main()
{
Company CompanyObj = new Company();
CompanyObj.FirstName = "Satish";
CompanyObj.LastName = "Reddy";
Console.WriteLine("Employee Full Name is : " + CompanyObj.FullName);
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response