All about Virtual,Override and New in C#

added by jalpesh
10/27/2013 7:07:43 AM

0 Kicks, 92 Views

have seen that lots of people get confused with Virtual, Override and new keyword in C#. So I thought it will be a good idea to write a blog post about it. In this blog post we will learn what is virtual, override and new keyword in C# and what’s difference between override and new in C#. Virtual and Override in C#: Virtual keyword allows class member to override in derived class. Let’s take simple example. I have class A which contains Print Method method as virtual method and I have another class B which is derived from class A which overrides Print method. Following is a code for that. public class A { public virtual void Print() { System.Console.WriteLine("Virtual Print method from a"); } } public class B:A { public override void Print() { System.Console.WriteLine("Override Print method from b"); } } Now If I create a object of class A like following and run the code Print method run as normal method. Following is code for for that. class Program { static void Main(string[] args) { A a=new A(); a.Print(); } } Once you run this it will have following outpu