new keyword in method signature

2019-01-02 23:16发布

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?

8条回答
劫难
2楼-- · 2019-01-02 23:47

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.

查看更多
老娘就宠你
3楼-- · 2019-01-02 23:49

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.

查看更多
登录 后发表回答