C# new Modifier

Summary: in this tutorial, you’ll learn about how to use the C# new modifier for the members of a subclass to explicitly hide a member with the same name from the base class.

Introduction to the C# new modifier

In inheritance, if a member of a subclass has the same name as the member of a base class, the C# compiler will issue a warning. For example:

class Person
{
    public string Name { get; set; }

    public string Introduce() => $"Hi, I'm {Name}.";
}

class Employee : Person
{
    public string JobTitle { get; set; }

    public string Introduce() => $"Hi, I'm {Name}. I'm a {JobTitle}.";
}Code language: C# (cs)

In this example:

  • The Person is the base class and the Employee is a subclass that inherits from the Person class.
  • Both Person and Employee classes have the same method Introduce() that returns a string.

C# compiler issues the following warning:

'Employee.Introduce()' hides inherited member 'Person.Introduce()'. Use the new keyword if hiding was intended.Code language: plaintext (plaintext)

It clearly indicates that the Introduce() method of the Employee class hides the Introduce() method of the Person class.

When a method in the subclass hides a member from the base class, the member in the subclass replaces the member of the base class.

Typically, you don’t want to hide a method of the base class. Usually, this happens by accident when you add a method to the base class with the same name as a method in the subclass. Therefore, the compiler issues the warning to help you recognize an unintended consequence earlier.

However, if you really want to hide a method from the base class, you can use the new modifier for the member in the subclass. For example:

class Person
{
    public string Name { get; set; }

    public string Introduce() => $"Hi, I'm {Name}.";
}

class Employee : Person
{
    public string JobTitle { get; set; }

    public new string Introduce() => $"Hi, I'm {Name}. I'm a {JobTitle}.";
}Code language: C# (cs)

In this example, we add the new modifier to the Introduce() method. The new modifier communicates our intent to the compiler and other developers that the duplicate Introduce() method is not an accident. Also, the new modifier suppresses the compiler warning.

Besides methods, you can use the new modifier for other members such as fields, properties, and indexers.

Summary

  • Use the C# new modifier for the members in the subclass to hide the members of a base class.
Was this tutorial helpful ?