CSharp - new versus override

Introduction

Consider the following class hierarchy:

class BaseClass{
       public virtual void Test()  { 
          Console.WriteLine ("BaseClass.Test"); 
       }
}
class Overrider : BaseClass{
       public override void Test() { 
          Console.WriteLine ("Overrider.Test"); 
       }
}
class Hider : BaseClass{
       public new void Test()      { 
          Console.WriteLine ("Hider.Test"); 
       }
}

The differences in behavior between Overrider and Hider are demonstrated in the following code:

Demo

using System;
class MainClass{// ww  w.j  a  va2s . c o m
   public static void Main(string[] args)
   {
        Overrider over = new Overrider();
        BaseClass b1 = over;
        over.Test();                         // Overrider.Test
        b1.Test();                           // Overrider.Test
        
        Hider h = new Hider();
        BaseClass b2 = h;
        h.Test();                           // Hider.Test
        b2.Test();                          // BaseClass.Test

   }
}
class BaseClass{
       public virtual void Test()  { 
          Console.WriteLine ("BaseClass.Test"); 
       }
}
class Overrider : BaseClass{
       public override void Test() { 
          Console.WriteLine ("Overrider.Test"); 
       }
}
class Hider : BaseClass{
       public new void Test()      { 
          Console.WriteLine ("Hider.Test"); 
       }
}

Result