C# New Modifier

New keyword (constructor invocation)

New methods are expected to hide base methods. The new modifier specifies that a method is supposed to hide a base method. It eliminates a warning issued by the compiler. No functionality is changed, but an annoying warning is silenced—and that's worth something.

Example

Note

This program introduces two classes, A and B. The B class derives from the A class. Class A has a public method Y, while class B has a public method Y that uses the new keyword to hide the base method Y.

This C# program uses the new modifier in a derived class. New eliminates a warning.

Program that uses new modifier [C#]

using System;

class A
{
    public void Y()
    {
	Console.WriteLine("A.Y");
    }
}

class B : A
{
    public new void Y()
    {
	// This method HIDES A.Y.
	// It is only called through the B type reference.
	Console.WriteLine("B.Y");
    }
}

class Program
{
    static void Main()
    {
	A ref1 = new A(); // Different new
	A ref2 = new B();
	B ref3 = new B();

	ref1.Y();
	ref2.Y();
	ref3.Y();
    }
}

Output

A.Y
A.Y
B.Y
Main method

Main method description. The main entry point uses the A and B types. With ref1, the base class is used directly; this results in the A.Y method being used. With ref2, the base class is used with a derived class; this results in the A.Y method being used again. This is because the override keyword is not used on B.Y. With ref3, the derived class is used directly; the "new" method B.Y is thus used.

Override Method

C# specification

The C# Programming Language

The annotated C# specification discusses the new modifier on page 433. The main reason the new modifier is included in the language is to instruct the compiler not to issue a warning when hiding is intended. Apparently, a common programming error occurs when a developer does not realize a method is actually hiding (not overriding) a base method.

The C# Programming Language: Specification

Summary

The C# programming language

In this article, we looked at the new modifier on a method in a derived type. We then demonstrated how the object hierarchy is used to locate the correct implementation to call in this situation. Finally, we looked at some reference material for the new modifier. The new modifier is completely different from the new class constructor.

New Class Instance Method Tips
.NET