new keyword in method signature

C#MethodsKeyword

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

New keyword reference from MSDN:

MSDN Reference

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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 MSDN for this.

Solution 5 - C#

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.

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution 8 - C#

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();

    }
}

Solution 9 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionp.campbellView Question on Stackoverflow
Solution 1 - C#KelseyView Answer on Stackoverflow
Solution 2 - C#BFreeView Answer on Stackoverflow
Solution 3 - C#Dan HerbertView Answer on Stackoverflow
Solution 4 - C#jonniiView Answer on Stackoverflow
Solution 5 - C#Don CheadleView Answer on Stackoverflow
Solution 6 - C#Robin ClowersView Answer on Stackoverflow
Solution 7 - C#Doug RView Answer on Stackoverflow
Solution 8 - C#OverfilledwaistcoatView Answer on Stackoverflow
Solution 9 - C#Simon MourierView Answer on Stackoverflow