Home >Backend Development >C++ >What Does the `new` Keyword Do in C# Method Signatures?
Understanding the "new" Keyword in Method Signatures
During a code refactoring, a developer mistakenly introduced a new keyword into a method signature:
private static new MyObject CreateSomething() { return new MyObject{"Something New"}; }
This validly compiles in C#, raising questions about the significance of the new keyword in method signatures.
What does the "new" keyword signify?
As mentioned in the MSDN documentation, the new keyword in a method signature modifies its referencing behavior:
Example:
Consider the following code:
public class A { public virtual void One(); public static void Two(); } public class B : A { public new void One(); public override 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
In this example, the class B redefines both the One method (using new) and the Two method (using override). By using new for One, class B hides the inherited implementation and introduces its own. However, by using override for Two, it overrides the inherited virtual method.
Therefore, the new keyword provides flexibility by allowing inherited methods to be overridden or hidden in cases where override is not applicable, such as for non-virtual and static methods.
The above is the detailed content of What Does the `new` Keyword Do in C# Method Signatures?. For more information, please follow other related articles on the PHP Chinese website!