Understanding “new” keyword in c#

new” keyword can be used as operator, modifier or constraint.

Using “new” keyword as operator.
New keyword is most commonly used for creating instance of a class/ types.
E.g.

var cc = new Class1(); 
int i = new int();
var query = from movie in Movies 
       select new {Name = movie.Name, ReleaseDate = movie.date};

Using “new” keyword as modifier.
New keyword hides a member that’s inherited from a base class. When we hide inherited member, the derived version of member replaces base class version.

E.g.1 Here we will see how can we replace methods using new keyword in c#

public class BaseClass
{
    public int a;
    public void MyMethod() 
{
// Some logic
 }
}
public class DerivedClass : BaseClass
{
    new public void MyMethod () 
{ 
// Some logic
}
}

Here MyMthod() from derived class will replace method from base class.
If we want to call method from base class then we have to use BaseClass.MyMethod() instead of just calling MyMethod()

E.g. 2 Here we will see how can we replace dataTypes values.

public class BaseClass
{
    public static int a = 100;
    public static int b = 50;
}

public class DerivedClass: BaseClass
{
    // Hide field 'a'. 
    new public static int a = 200;

    static void Main()
    {
        // Display the new value of a:
        Console.WriteLine(a);

        // Display the hidden value of a:
        Console.WriteLine(BaseClass.a);

        // Display the unhidden member a:
        Console.WriteLine(b);
    }
}

Here we can see that we are replacing value of variable “a” in derived class.
As shown above If we want to use variable value from base class then we have to use “BaseClass.a” instead of “a”.

Using “new” as Constraint
New constraint specifies that any type argument in a generic class declaration must have a public parameter less constructor. To use the new constraint, the type cannot be abstract.

E.g.

    class ItemFactory<T> where T : new()
    {
        public T GetNewItem()
        {
            return new T();
        }
    }

admin