Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
4.00/5 (5 votes)
See more:
What is meant by Virtual Keyword in C#?
Posted

To put in one line (if you are familiar with OOPS concepts and subclassing) -
abstract - Must be overriden
virtual - can be overriden
sealed - cannot be overriden
 
Share this answer
 
Comments
Albin Abel 8-Apr-11 2:28am    
It rules. :) My 5. "if you are familiar with OOPS concepts and subclassing"= OP is learning Oops from your answer. He would be appreciate your helps. :)
Abhinav S 8-Apr-11 6:07am    
Thank you.
Selva Ganesh 27-Jan-15 7:58am    
ok
Selva Ganesh 27-Jan-15 7:59am    
nandrigal pala
Isuru Nanayakkara 14-Jul-12 1:56am    
I didn't know about the 'sealed' keyword! Thank you.
What is the virtual keyword used for?

Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.

When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.

public class Employee
{
  public virtual void SetBasic(float money) //This method may be overriden
  { Basic += money; }
}


public class Manager : Employee
{
  public override void SetBasic(float money) //This method is being overriden
  {
   float managerIncentive = 10000;
   base.SetSalary(money + managerIncentive); //Calling base class method
  }
}
 
Share this answer
 
Comments
Abhinav S 8-Apr-11 0:56am    
Good explanation. My 5.
Mahendra.p25 8-Apr-11 1:01am    
Thanks
Abhinav S 8-Apr-11 1:02am    
You are welcome.
SwitcherSoft 8-Apr-11 2:42am    
yes
Member 9829004 3-Apr-13 1:51am    
thanks
Hi
If you have some doubts in these links you may specifically ask here. We will be glad to answer.

http://msdn.microsoft.com/en-us/library/9fkccyh4%28v=vs.71%29.aspx[^]

http://www.akadia.com/services/dotnet_polymorphism.html[^]

cheers
 
Share this answer
 
Comments
Abhinav S 8-Apr-11 1:01am    
Good links. 5.
Albin Abel 8-Apr-11 2:23am    
Thanks Abhinav
[no name] 22-Jun-13 2:38am    
second one is good link . Thanks a lot ......
Member 8406857 12-Feb-14 1:56am    
Apart from your overiding concept where we use this Virtual keyword?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900