Understanding the 'new' Keyword in C#

C# new Keyword

The new keyword is used for various purposes, depending on the context in which it is used. The new keyword is not limited to a single use case, and it serves different functions in different scenarios. Here are some common uses of the new keyword in C#:

Creating Objects (Instantiation):

The primary use of the new keyword is to create instances (objects) of classes. When you want to create an object of a particular class, you use the new keyword followed by the class name and parentheses. This calls the class's constructor and allocates memory for the object.

// Creating an instance of the ExampleClass.
ExampleClass obj = new ExampleClass();

Method Hiding (Overriding):

The new keyword can also be used to hide a method with the same name in a base class (a method from the parent class) when you're creating a method with the same name in a derived class. This is known as method hiding, not method overriding.

class BaseClass
{
    public void Display()
    {
        Console.WriteLine("BaseClass Display method");
    }
}

class DerivedClass : BaseClass
{
    public new void Display()
    {
        Console.WriteLine("DerivedClass Display method");
    }
}

// Usage example:
DerivedClass obj = new DerivedClass();
obj.Display(); // Output: "DerivedClass Display method"

Explicit Interface Implementation:

In C#, when a class implements multiple interfaces that have a method with the same signature, you can use the new keyword to explicitly implement the interface method for one of the interfaces.

interface IInterface1
{
    void Display();
}

interface IInterface2
{
    void Display();
}

class ExampleClass : IInterface1, IInterface2
{
    // Explicitly implementing the method for IInterface1.
    void IInterface1.Display()
    {
        Console.WriteLine("IInterface1 Display method");
    }

    // Explicitly implementing the method for IInterface2.
    void IInterface2.Display()
    {
        Console.WriteLine("IInterface2 Display method");
    }
}

// Usage example:
ExampleClass obj = new ExampleClass();
((IInterface1)obj).Display(); // Output: "IInterface1 Display method"
((IInterface2)obj).Display(); // Output: "IInterface2 Display method"

These are some of the main uses of the new keyword in C#. It's essential to understand the context in which you are using it, as it can have different implications depending on the situation.