Pages

Monday, April 7, 2014

The differece between "new" and "override"

However the keyword new and the keyword override are very alike, they have some really different purpose and it is not recommended to swap / mix them. You can read their behaviors and purposes e.g. on StackOverflow

Here is an example for the article above. As you can see, you will have different result, which can cause you some headache if you try to find a bug.

   public class Base
   {
      public virtual void Method()
      {
         Debug.WriteLine("Base");
      }
   }

   public class Override : Base
   {
      public override void Method()
      {
         Debug.WriteLine("Override");
      }
   }

   public class New : Base 
   {
      public new void Method()
      {
         Debug.WriteLine("New");
      }
   }

   public class Program
   {
      public Program()
      {
         var b = new Base();
         b.Method(); // "Base"

         b = new Override();
         b.Method(); // "Override"
         
         b = new New();
         b.Method(); // "Base"
      }

      static void Main(string[] args)
      {
         var p = new Program();
      }
   }

Unfortunately C# compiler has a really bad behavior and let you to hide a method without explicitly write new. Ohh, yeah... you will get a warning, but not a compile error nor a runtime error. All you are going to face with, is some unwanted misbehavior. So, watch out.

No comments:

Post a Comment