new keyword in method signature

p.campbell picture p.campbell · Jun 18, 2009 · Viewed 83.6k times · Source

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?

Answer

Kelsey picture Kelsey · Jun 18, 2009

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.