124

While performing a refactoring, I ended up creating a method like the example below. The datatype has been changed for simplicity's sake.

I previous had an assignment statement like this:

MyObject myVar = new MyObject();

It was refactored to this by accident:

private static new MyObject CreateSomething()
{
  return new MyObject{"Something New"};
}

This was a result of a cut/paste error on my part, but the new keyword in private static new is valid and compiles.

Question: What does the new keyword signify in a method signature? I assume it's something introduced in C# 3.0?

How does this differ from override?

Filburt
  • 17,626
  • 12
  • 64
  • 115
p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • 5
    Some notes on the desirability of method hiding: http://blogs.msdn.com/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx – Eric Lippert Jun 18 '09 at 19:49
  • 2
    @Eric.. Great post. I never thought of method hiding in that way, as in yes, the object IS one thing, but we are now presenting it as something else, so we want the behavior of the thing we're presenting it AS. Clever... – BFree Jun 18 '09 at 20:01
  • 1
    A duplicate question in the future and I've tried answering in some detail: [Use new keyword in c#](http://stackoverflow.com/questions/15803965/use-new-keyword-in-c-sharp/15804023#15804023) – Ken Kin Apr 07 '13 at 10:33
  • 1
    The use of `new` as a a modifier on a method (or other type member) is not "something introduced in C# 3.0". It has been there ever since the first version of C#. – Jeppe Stig Nielsen Aug 16 '13 at 10:32
  • @jeppe you've basically repeated some of the answers below with your comment. – p.campbell Aug 18 '13 at 21:09
  • http://stackoverflow.com/questions/9201344/is-using-new-keyword-in-method-signature-generally-just-for-readability – Don Cheadle Jun 22 '15 at 22:31
  • 1
    There's like 4 duplicates of this question in SO. In my opinion, this one will give you best understanding: https://stackoverflow.com/questions/3117838/why-do-we-need-the-new-keyword-and-why-is-the-default-behavior-to-hide-and-not-o. It is answered by @EricLippert. – Raikol Amaro Oct 16 '19 at 15:15

9 Answers9

114

new modifier reference from MSDN.

And here is an example I found on the net from a Microsoft MVP that made good sense (link to original):

public class A
{
   public virtual void One();
   public void Two();
}

public class B : A
{
   public override void One();
   public new void Two();
}

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B

override can only be used in very specific cases. From MSDN:

You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

So the new keyword is needed to allow you to 'override' non-virtual and static methods.

Hugh W
  • 716
  • 2
  • 10
  • 33
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • 4
    i just run your sample.. it will override even you don't specify "new", right? – Michael Sync Dec 14 '11 at 10:07
  • 2
    @MichaelSync exactly,so why do we need to mention new keyword? – ZoomIn Jul 17 '13 at 07:05
  • 4
    "Although you can hide members without using the new modifier, you get a compiler warning." per the linked doc. So, the keyword makes it clear you intended the hiding, and the warning is not issued. – Jim Counts Mar 06 '15 at 15:18
  • 3
    -1 -> it's not required at all -- the behavior will be the same. Very confusing to a newbie what `new` is about, but I think it's literally only there for readability - the compiler is simply warning you that when you call derived class method of same name as base, you won't get the base class's method that you may think.... it's bizarre... purely for readability? – Don Cheadle Jun 22 '15 at 22:17
  • http://stackoverflow.com/questions/9201344/is-using-new-keyword-in-method-signature-generally-just-for-readability – Don Cheadle Jun 22 '15 at 22:31
  • 1
    For the sake of completeness: If both the A and B class implement an interface `IMyInterface` the implementation on the Derived class will be called. Thus `IMyInterface c = new B()` will call the implementation of the B class. If only one class implements the interface, the method from the class that implements it, will be called. – Nullius Nov 17 '15 at 21:43
  • 1
    I think this is an incorrect statement: "So the 'new' keyword is needed to allow you to 'override' non-virtual and static methods." The 'new' keyword doesn't override the method; if it did, then your call to a.Two() would call the implementation in B. – Raikol Amaro Oct 16 '19 at 14:46
65

No, it's actually not "new" (pardon the pun). It's basically used for "hiding" a method. IE:

public class Base
{
   public virtual void Method(){}
}

public class Derived : Base
{
   public new void Method(){}
}

If you then do this:

Base b = new Derived();
b.Method();

The method in the Base is the one that will be called, NOT the one in the derived.

Some more info: http://www.akadia.com/services/dotnet_polymorphism.html

Re your edit: In the example that I gave, if you were to "override" instead of using "new" then when you call b.Method(); the Derived class's Method would be called because of Polymorphism.

BFree
  • 102,548
  • 21
  • 159
  • 201
  • public class Base { public virtual void Method() { Console.WriteLine("Base"); } } public class Derived : Base { public void Method() { Console.WriteLine("Derived"); } } Base b = new Derived(); b.Method(); I got "Base".. If I add "new" in Derived class, I still get "Base".. – Michael Sync Dec 14 '11 at 09:50
  • @michael the method is still virtual – Rune FS Dec 14 '11 at 10:18
  • @MichaelSync: You should be seeing a warning with that code; Warning Derived.Method()' hides inherited member 'Base.Method()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. – Chris McAtackney Dec 14 '11 at 10:21
  • 2
    @MichaelSync If the word "override" is left out, then the default behavior is "new" e.g. method hiding. So the fact that you're leaving the word new out makes no difference. – BFree Dec 14 '11 at 14:43
  • 1
    Yes. That's what I think as well. Not sure why C# added "new" keyword.. it's just for making the warning disappeared.. http://stackoverflow.com/questions/8502661/new-keyword-in-c-sharp-is-just-for-making-the-warning-disappeared-isnt-it – Michael Sync Dec 15 '11 at 03:24
  • For the sake of completeness: If both the Base and Derived class implement an interface `IMyInterface` the implementation on the Derived class will be called. Thus `IMyInterface i = new Derived()` will call the implementation of the Derived class. If only one class implements the interface, the method from the class that implements it, will be called. – Nullius Nov 17 '15 at 21:45
  • @MichaelSync I think they use "new" keyword because, although the method has the same name as the one in the base class, it is a completely new (not inherited) method and has nothing to do with the one in the base class. It's just like any other method specific to derived class, but since it's name matches the one in base class we have to explicitly say that we did not forget the keyword "override" and our choice of method name is not because of overriding. – Almir Dec 18 '19 at 10:59
25

As others explained, it is used to hide an existing method. It is useful for overriding a method that isn't virtual in the parent class.

Keep in mind that creating a "new" member is not polymorphic. If you cast the object to the base type, it will not use the derived type's member.

If you have a base class:

public class BaseClass
{
    public void DoSomething() { }
}

And then the derived class:

public class DerivedType : BaseClass
{
    public new void DoSomething() {}

}

If you declare a type of DerivedType and then cast it, the method DoSomething() isn't polymorphic, it will call the base class' method, not the derived one.

BaseClass t = new DerivedType();
t.DoSomething();// Calls the "DoSomething()" method of the base class.
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • 1
    It will call the method from base class even you remove "new" from DerievedType as well.. – Michael Sync Dec 14 '11 at 09:51
  • 2
    I think your second paragraph nails this entire topic. When dealing with calls from a **base class reference**, "new" is not polymorphic... ie. You get exactly what *you* specify when you make the call. "override" is polymorphic...ie. You get what the *class hierarchy* specifies. – Jonathon Reinhart May 01 '12 at 19:08
  • how is this something so vaguely defined? Very frustrating for a newbie. And no, it has nothing to do with polymorphism -- it has the exact same behavior as simply not having `override` in method signature – Don Cheadle Jun 22 '15 at 22:19
  • What is hidden from what? It surely can't be that `new` hides the base type from the derived type, because can't you always access the base type using the `base.` notation? – thatWiseGuy Sep 12 '17 at 20:13
  • @thatWiseGuy It's "hidden" in the sense that the base method won't be called when using the derived class in your code. It can still be called internally using `base.`, and can also be called externally if you cast to the base type in your code. It's more technically accurate to think of it as "overriding" the base method than "hiding" it. – Dan Herbert Sep 13 '17 at 20:50
9

From the docs:

If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.

What this means in practice:

If you inherit from another class and you have a method that shares the same signature you can define it as new so that it independent from the parent class. This means that if you have a reference to the 'parent' class then that implementation will be executed, if you have a reference to the child class then that implementation will be executed.

Personally I try to avoid the new keyword as it normally means I've got my class hierarchy wrong, but there are times when it can be useful. One place is for versioning and backwards compatibility.

There's lot of information in the Microsoft reference.

Hugh W
  • 716
  • 2
  • 10
  • 33
jonnii
  • 28,019
  • 8
  • 80
  • 108
  • 1
    The fact that this behavior occurs has nothing to do with `new` being there. It is syntactic/readability. – Don Cheadle Jan 20 '16 at 15:57
  • Well, that quote makes a lot of sense to me. It would be great if someone else can verify that information. The link is dead. – carloswm85 Jun 19 '22 at 02:18
7

Long story short -- it's NOT required, it changes NO behavior, and it is PURELY there for readability.

That's why in VS you will see a little squiggly, yet your code will compile and run perfectly fine and as expected.

One has to wonder if it was really worth creating the new keyword when all it means is the developer's acknowledging "Yes, I know I'm hiding a base method, yes I know I'm not doing anything related to virtual or overriden (polymorphism) -- I really want to just create it's own method".

It's a bit bizarre to me, but maybe only because I come from a Java background and there's this fundamental difference between C# inheritance and Java: In Java, methods are virtual by default unless specified by final. In C#, methods are final/concrete by default unless specified by virtual.

Don Cheadle
  • 5,224
  • 5
  • 39
  • 54
4

It means the method replaces a method by the same name inherited by the base class. In your case, you probably don't have a method by that name in the base class, meaning the new keyword is totally superfluous.

Robin Clowers
  • 2,150
  • 18
  • 28
1

From MSDN:

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
Doug R
  • 5,749
  • 2
  • 28
  • 32
0

Be careful of this gotcha.
You have a method defined in an interface that is implemented in a base class. You then create a derived class that hides the interface's method, but don't specifically declare the derived class as implementing the interface. If you then call the method via a reference to the interface, the base class's method will be called. However if your derived class does specifically implement the interface, then its method will be called whichever type of reference is used.

interface IMethodToHide
{
    string MethodToHide();
}

class BaseWithMethodToHide : IMethodToHide
{
    public string MethodToHide()
    {
        return "BaseWithMethodToHide";
    }
}

class DerivedNotImplementingInterface   : BaseWithMethodToHide
{
    new public string MethodToHide()
    {
        return "DerivedNotImplementingInterface";
    }
}

class DerivedImplementingInterface : BaseWithMethodToHide, IMethodToHide
{
    new public string MethodToHide()
    {
        return "DerivedImplementingInterface";
    }
}

class Program
{
    static void Main()
    {
        var oNoI = new DerivedNotImplementingInterface();
        IMethodToHide ioNoI = new DerivedNotImplementingInterface();

        Console.WriteLine("reference to the object type DerivedNotImplementingInterface calls the method in the class " 
            + oNoI.MethodToHide());
        // calls DerivedNotImplementingInterface.MethodToHide()
        Console.WriteLine("reference to a DerivedNotImplementingInterface object via the interfce IMethodToHide calls the method in the class " 
            + ioNoI.MethodToHide());
        // calls BaseWithMethodToHide.MethodToHide()
        Console.ReadLine();

        var oI = new DerivedImplementingInterface();
        IMethodToHide ioI = new DerivedImplementingInterface();

        Console.WriteLine("reference to the object type DerivedImplementingInterface calls the method in the class " 
            + oI.MethodToHide());
        // calls DerivedImplementingInterface.MethodToHide()
        Console.WriteLine("reference to a DerivedImplementingInterface object via the interfce IMethodToHide calls the method in the class " 
            + ioI.MethodToHide());
        // calls DerivedImplementingInterface.MethodToHide()
        Console.ReadLine();

    }
}
0

FWIW, I've been writing C# code for quite a time now, and the only case where I needed the new keyword was the following OO hierarchy scenario:

public abstract class Animal
{
    protected Animal(Animal mother, Animal father)
    {
        Mother = mother;
        Father = father;
    }

    public Animal Mother { get; }
    public Animal Father { get; }
}

public class Dog : Animal
{
    public Dog(Dog mother, Dog father)
        : base(mother, father)
    {
    }

    public new Dog Mother => (Dog)base.Mother;
    public new Dog Father => (Dog)base.Father;
}

Few remarks:

  • No OO rule is broken, base classes still work fine.
  • Properties are not marked virtual on purpose, they don't need to be.
  • In fact we enforce more OO rules thanks to the new keyword: a dog cannot have any animal as a father/mother. It must be a dog.
  • the new keyword is used because we cannot "override" a property (or method) just by changing its return type. new is the only way to have a nice OO hierarchy.
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298