posts - 268, comments - 104, trackbacks - 127

My Links

News

My main blog url now is: weblogs.asp.net/meligy

Tag Cloud

Article Categories

Archives

Post Categories

BlogRoll

About Me:

The C# Modifier 'new'

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

                        ("\n\nThe 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:
the C# new Keyword result of code

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 Library >  Development Tools and Languages >  Visual Studio .NET >  Visual Basic and Visual C# >  Reference >  Visual C# Language >  C# Programmer's Reference >  C# Keywords >  Operator Keywords > new.

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

 

Print | posted on Thursday, April 07, 2005 11:28 PM |


Feedback

# re: The C# Modifier 'new'

I would like to know what rules are applied to a method or variable when you use the virtual keyword...

Ie: If I use the virtual Keyword, do I have to override the method...

Thank you.
Please reply to antsays@gmail.com 4/21/2005 9:00 PM | Anthony

# re: The C# Modifier 'new'

Excellent and very helpful.

Thanks
Danny 12/17/2005 11:45 PM | Danny

# re: The C# Modifier 'new'

Urs explaination is really helpful..

Thanks
Shyam 1/4/2006 6:59 AM | Shyam

# re: The C# Modifier 'new'

I just read some books but none of them explain the difference. Your example is good enough for me to understand. Thanks.

2/20/2006 7:15 PM | k

# re: The C# Modifier 'new'

Thanks, well written. I just discovered this power of the new keyword, and you answered my questions about methods. 3/15/2006 1:49 PM | Adam

# re: The C# Modifier 'new'


Thanks, a good explanation on this has not been easy to find. 10/3/2006 1:56 PM | Ronnie Mukherjee

# re: The C# Modifier 'new'

Very useful.

An interesting side effect: add this method to class Implementor:
public void TestMethod(Base b)
{
b.ViewNew();
}
and then call it with myChild as argument:
Implementor imp = new Implementor();
imp.TestMethod(myChild);
The called method is Base's ViewNew, not myChild's, because the argument has type Base. Somewhat unexpected, but consistent with this article. 4/6/2007 10:04 PM | Jaume Llardén

# re: The C# Modifier 'new'

Well, it's expected. This is one of the two key properties of this approach:
1- It's only called when the object reference is of the child's type, not the parent.
2- It doesn't require that the parent have explicit "virtual" in definitions. 4/6/2007 10:14 PM | Mohamed Ahmed Meligy

# re: The C# Modifier 'new'

Good article. I still don't understand the situation whereby the 'new' keyword would be beneficial.

In your code example, if you take out the 'new' keyword from the ViewNew() method, it works exactly the same way! Without the new keyword the method is still effectively hidden within the Child class.

i.e. public void ViewNew() is the signature in both classes.

Do you understand where I'm coming from? Thanks 6/6/2007 2:35 PM | LiamW

# re: The C# Modifier 'new'

I know what you are talking about.
If you don't use it, the complier won't be 100% silent though. It'll give you a compile warning. This is part of C# nature being somewhat (and only somewhat) verbose (you know, code readability issues and such).
The warning will say that you should be using "new" on the method, but after all, it's not a compilation error, so, -unless somebody has set some code policy against that- you can still compile/run your code. 6/6/2007 5:20 PM | Mohamed Ahmed Meligy

# re: The C# Modifier 'new'

got it! your're explanation was perfect. Thanks. 12/14/2007 10:46 AM | Diann

# re: The C# Modifier 'new'

Hey...

Explanation is good.. thanks! 2/14/2008 7:41 PM | Rosa

# re: The C# Modifier 'new'

Hi ,
Its explained very clearly...
the code samples with comments are excellent...

thanks a lot for the good article and ur effort

2/19/2008 7:22 AM | Rama charan

# re: The C# Modifier 'new'

easiest explanation i have read. 6/12/2008 6:06 AM | Shy bald bhuddist

# re: The C# Modifier 'new'

class base
{
int i,j;
public virtual function 1()
}
class derived:base
{
int p,q;
public override fucntion 1()
}

static void main()
{
base obj = new base(); -------1
base obj2 = new derived();-------2
}


In second instance[ base obj2 = new derived(); ] Can you explain how the reference of the base type is holding the object of the derived type.

6/14/2008 11:00 AM | Mohammad Aamir

# re: The C# Modifier 'new'

This is what inheritance is all about :).

So, assume base is Animal and child is Dog. Actually the word child is misleading but frequent, as "child" is just "customization" .

What is happening here is that you ask me for an animal in a box, and I give u a dog, u do not know it it a dog and will not ask it to park for example, but you know it is an animal.

Same here, when referring to child as base, we only know the things it has from base class. In memory it still is complete child and if we use child reference again we can refer to child properties, but, when using the base reference, we only know about what it inherits from base.. 6/14/2008 12:24 PM | Mohamed Ahmed Meligy

# re: The C# Modifier 'new'

This article is reallly good , i have learnt the concept very clearly . Thanks for ur explanation. Hope u article would be helping to all new learners. looking forward for further concepts in ur words 6/19/2008 6:30 PM | sunitha

# re: The C# Modifier 'new'

Hey sunitha,
Do u suggest any certain concepts to talk about ? :) 6/19/2008 6:33 PM | Mohamed Ahmed Meligy

# re: The C# Modifier 'new'

Thanks Mr.Meligy.
Your explanation was really helpful. I will come up with more questions ahead. 7/3/2008 8:21 PM | Mohammad Aamir

# re: The C# Modifier 'new'

Realy very good Expla........... 10/5/2008 12:29 PM | RAVI KUMAR

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 8 and 7 and type the answer here:

Powered by: