New Keyword in C# - ProgramIdea

New keyword in C#


Generally new keyword is use to create instance of the class or simply call the constructor. New keyword is the one of the most frequently using keyword by most of developers. It can also use in linq to create anonymous type instance in other words in linq's projection. By help of new keyword, we can hide base class member in derived class.

Creating instance of class

New keyword is use to create instance of class or calling constructor.


TestClass obj = new TestClass();

In Linq for projection

In linq, new keyword is use for projection means creating anonymous type instance.

var data = from i in db.tbl_students
           select new
           { 
               StudentName = i.Name,
               BranchName = i.Branch,
               CityName = i.City
           };

Hiding base class member in derived class

We can hide base class member in derived class using new keyword. You can also hide base class member in derived class without using new keyword but in this case you get a compiler warning. So to prevent from warning we use new keyword.

// base class
public class ParentClass
{
    public void SayHello()
    {
        Console.WriteLine("Hello from parent class");
    }
}

// derived class
public class ChildClass : ParentClass
{
    new public void SayHello()
    {           
        Console.WriteLine("Hello from child class");
    }
}

// If you not using new keyword then you get below warning
// Warning   
// ChildClass.SayHello()' hides inherited member ParentClass.SayHello()'.
// Use the new keyword if hiding was intended.