The C# Modifier ‘new’

Note:
This is ported from my old weblog. Originally published April 07, 2005

There was a question in Microsoft Forums regarding the new modifier in C# and what’s the difference between using it and using the virtual and override modifiers. I wanted to share that here as well.

The new modifier is mainly used for hiding the non virtual methods. Unlike override modifier, it’s used to hide all class members not only methods (i.e. variables and properties). If you create a Base class with a protected, internal or public int for example, and inherit that Base in another class called Child, placing another x in it and try to compile this, the code will compile successfully! However, if you look at the tasks window (assuming that you are using VC#) you’ll see a warning that you should use the new keyword with the second declaration. A simple code should tell you what I mean here:

using System;
namespace ConsoleView
{
      public class Base
      {
            //The original member
            public int x;
      }
      public class Child:Base
      {      
            //This declaration will compile well, but,
            //will generate the following warning :
            //%CodeFilePAth%(%LineNumber%):
            //The keyword new is required on 'ConsoleView.Child.x'
            //because it hides inherited member 'ConsoleView.Base.x'
            public int x; 
      } 
}

Anyway, this is not the primary purpose for the modifier. The main purpose comes when you use it to hide a method instead of using override (by the way, to hide a method, you can’t use both override and new. This gives you an error not just a waning).

Using virtual and override modifiers will always be similar to using the new modifier except that when you use virtual and override you can’t call the the Base class except from inside the Child class itself (meaning from the Child class methods only). To make this clearer, if you cast the child as Base and call the virtual method, you’ll still get the overriden version not the vertual (original) one. This happens becasue override totally replaces the Base virtual method. It doesn’t just hide it.

Now, if you leave the original Base method with or without the virtual modifier (it doesn’t matter here), and use the new modifier with the Child version of this method, you’ll be hiding the original method only when Child is treated as a Child (Not casted as Base). If you cast it as Base, and call the same method, you’ll get the original version of the method, not the new one.

If you feel confused, check the following code segment:

using System;
namespace ConsoleView
{
      //This holds only original versions of the methods
      public class Base
      {
            //This method will be overriden by Child, so, it'll never execute
            public virtual void View()
            {
                  Console.WriteLine("Viewing Base, Original virtual View");
            }
 
            //This method will be hidden only from inside Child (using 'new' modifier)
            //Note that I could make it virtual too, this wouldn't change anything
            public void ViewNew()
            {
                  Console.WriteLine("Viewing Base, Original OLD ViewNew ;)");
            }
      }
 
      //this class holds all the edited versions of methods
      public class Child:Base
      {    
            //Here I use override to permanently replace the original method
            //Whatever the reference type is,
            //    this'll always be the method executed when you call View()
            public override void View()
            {
                  Console.WriteLine("Viewing Child, override View");
            }
 
            //this hides the method only if the refernce type is Child or inherited from Child
            //a call from a reference of type Base will execute the OLD method, not thiis one
            public virtual new void ViewNew()
            {
                  Console.WriteLine("Viewing Child, new View");
            }
      }
 
      /// Used to hold the 'Main' method only!
      /// to show up the result of using each in the Console
      class Implementor
      {
            /// The main entry point for the application.
            /// Used to show up what's the expected result.
            [STAThread]
            static void Main(string[] args)
            {
                  //This part is very typical
                  //Creating a Child reference, and it referes to (its value is) a child
                  Child myChild=new Child();
                  //Indicating reference and value types in the output
                  Console.WriteLine
                        ("The reference now is a Child that refers to a child. Typical, ha?!");
                  //Will show up the overriden version
                  //as it has been totally overriden using the override modifier
                  myChild.View();
                  //Shows up the new version,
                  //as the new modifier hid the original version
                  myChild.ViewNew();
 
                  //The difference comes here
                  //The reference is a Base, but it refers to (its value is) a Child
                  Base myBase=(Base)new Child();
                  //Indicating the previous change in the output
                  Console.WriteLine
                        ("nnThe reference now is a Base, yet it still refers to a child");
                  //Will show the overriden version,
                  //even though the reference is of type Base,
                  //it's been totally overriden, not just hdden
                  myBase.View();
                  //Will show the original version NOT the new one
                  //as the new hides the method in Child only
                  //it doesn't override it totally
                  myBase.ViewNew();
 
                  //Just to halt the screen so that I can read the output
                  Console.Read();
            }
      }
}

This code should be explainning itself on its own. I just show that when I call the virtual method ‘View()’ using a Child reference or Base refernce, I always get the overriden version, on the other hand, when I call the ‘ViewNew()’ method using a Base reference, I get the original version. I get the “new” version only when I use a Child reference (or reference of any type that is inherited from Child itself).

This should be the output of that program:

c-sharp-new

A good remark is that a method can be new and virtual at the same time, just in case you wanted to allow others to override your new method, especially if the old method is not a virtual one ;)

If you are seeking the official word from MSDN, Check MSDN LibraryDevelopment Tools and LanguagesVisual Studio .NETVisual Basic and Visual C#ReferenceVisual C# LanguageC# Programmer’s ReferenceC# KeywordsOperator Keywords > new.

Finally, just tell me if this is too much, causes you confusion, or just never helped you by any means!

 

Technorati Tags: C#,CSharp,OOP
Share With Friends:

How did I learn that?

As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.

It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.

Take it for a test ride, and you may unsubscribe any time.

You might also want to support me by checking these out [Thanks]:

  • You should probably use an ASP.NET example instead of a Windows Console application since your are bloggin from weblogs.asp.net. Just a suggestion.

  • First, this is port of an old post. I’ve stated that above!!!

    Also, for such language stuff, the Console is the best to explain this stuff. That’s what most instructors claim anyway :).

    “ince your are bloggin from weblogs.asp.net.”
    I’ve contacted Joe about whether I can even post personal stuff here. He said it is OK. I really hope it is, and I wasn’t mistaken by porting my stuff here.

  • http://

    Good one, thanks.

  • Rob

    I agree totally … that a Console Application is by far the best way to demonstrate the principles that you’re explaining. Overloading the sample with a load of ASP.net “cruft” would take away from the ease of understanding.

    Although – a good asp.net-ised example of this would be a custom control that inherits from one provided by the framework, perhaps? :)

  • Oh yeah, that example would pretty much help keep the reader’s focus on the article’s point best :D :C :)

  • http://

    Yes its good example to eliminate confusions… and i suggest console is the right option as most of MSDN also based on it