Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0140 new and virtual

We can mark virtual member with new keyword. The different is shown in the following code. using System; public class BaseClass { public virtual void MyMethod() { Console.WriteLine("BaseClass.MyMethod"); } } public class Overrider : BaseClass { public override void MyMethod() { Console.WriteLine("Overrider.MyMethod"); } } public class Hider : BaseClass { public new void MyMethod() { Console.WriteLine("Hider.MyMethod"); } } class Program { static void Main(string[] args) { Overrider over = new Overrider(); BaseClass b1 = over; over.MyMethod(); Hider h = new Hider(); BaseClass b2 = h; h.MyMethod(); } } The output: Overrider.MyMethod Hider.MyMethod