I have been programming in C++ for sometime and now I am starting to work with C# but I cannot get the idea of virtual and override keywords. Since the pointers and all related to it’s stuff is mostly gone from C++ we do not really need them do we ? Or I am missing some major points of C# programming.
Example :
namespace ConsoleApplication1
{
public class Employee
{
public virtual void GetPayCheck()
{
Console.WriteLine("employee gets his pay check ");
}
public void Work()
{
Console.WriteLine("employee works ");
}
}
public class Manager : Employee
{
public override void GetPayCheck()
{
Console.WriteLine("MANAGER gets his pay check ");
}
}
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee();
Manager exec = new Manager();
emp.Work();
exec.Work();
emp.GetPayCheck();
exec.GetPayCheck();
}
}
}
Even if I omit virtual or override keywords ( or both ) I still get the same output.
What am I
Using
virtualandoverrideallows you to completely replace theWorkmethod, regardless of what type the variable is declared as. If a method is declared as virtual, the CLR checks if the object is a derived class and if the method has been overridden. If a method is not virtual, the CLR just calls the method with the nameWorkfrom the type that the object has been declared as.