What is the difference between the override and new keywords in C#?

Viewed 42650

What is the difference between the override and new keywords in C# when defining methods in class hierarchies?

6 Answers

Looks like an old question, let me try a different answer:

  1. new : as the name says, it is a new member in the family of inheritance hierarchy and this will be used as base member for further down the chain (if marked as virtual).

  2. override : It means I don't accept my parent class' member implementation and I will do differently.

Consider the following class hierarchy:

using System;

namespace ConsoleApp
{     
     public static class Program
     {   
          public static void Main(string[] args)
          {    
               Overrider overrider = new Overrider();
               Base base1 = overrider;
               overrider.Foo();
               base1.Foo();

               Hider hider = new Hider();
               Base base2 = hider;
               hider.Foo();
               base2.Foo();
          }   
     }   

     public class Base
     {
         public virtual void Foo()
         {
             Console.WriteLine("Base      => Foo");
         }
     }

     public class Overrider : Base
     {
         public override void Foo()
         {
             Console.WriteLine("Overrider => Foo");
         }
     }

     public class Hider : Base
     {
         public new void Foo()
         {
             Console.WriteLine("Hider     => Foo");
         }
     }
}    

Output of above codes must be:

Overrider => Foo
Overrider => Foo

Hider     => Foo
Base      => Foo
  • A subclass overrides a virtual method by applying the override modifier:
  • If you want to hide a member deliberately, in which case you can apply the new modifier to the member in the subclass. The new modifier does nothing more than suppress the compiler warning that would otherwise result

The simple difference is that override means the method is virtual (it goes in conduction with virtual keyword in base class) and new simply means it's not virtual, it's a regular override.

So both really are function overrides, one is with virtual characteristics, the other not.

What does mean exactly? It simply means polymorphism will not be in play for `new' methods.

The following image illustration might make this clear.

enter image description here

Note if you don't use new keyword, it is still implied but it will generate a warning message.

Related