new Operator Used to create objects and invoke constructors.
// Create objects and invoke constructors
Class1 obj = new Class1();
// Create instances of anonymous types
var employee = new { EmpID = 3, Name = "Bruce", Gender = Gender.Male};
// invoke the default constructor for value types
int i = new int();
// invoke the default constructor for value types with default value
int i = 0;
new Modifier Used to hide an inherited member from a base class member.
class ParentClass
{
public int x = 5;
public void Work()
{
for (int i = 0; i < x; i++) Console.WriteLine("Parent work : " + i);
}
public decimal Caculate()
{
return x + x;
}
}
class ChildClass : ParentClass
{
public new int x;
public new void Work()
{
for (int i = 0; i < x; i++) Console.WriteLine("Child work : " + i);
}
public new decimal Caculate()
{
return base.x + this.x;
}
}
class Program
{
static void Main(string[] args)
{
ParentClass p = new ParentClass();
p.Work();
// Parent work : 0
// Parent work : 1
// Parent work : 2
// Parent work : 3
// Parent work : 4
Console.WriteLine(p.Caculate());
// 10
Console.WriteLine("================");
ChildClass c = new ChildClass() { x = 3 };
c.Work();
// Child work : 0
// Child work : 1
// Child work : 2
Console.WriteLine(c.Caculate());
// 8
}
}
new Constraint Used to restrict types that might be used as arguments for a type parameter in a generic declaration.
class MyCollection<T> where T : new()
{
// Type T must have a public parameterless constructor
}
class MyCollection2<T> : IEnumerable<T> where T : IDisposable, new()
{
// Type T implements IDisposable and must have a public parameterless constructor,
// the new() constraint must at last
}