C# – New

New Operator/Modifier/Constraint

new keyword can be used for operator, modifier, constraint.

New Operator

1. Is used to create objects and invoke constructors.

Class1 obj = new Class1();

2. Used to create instances of anonymous types.

var query = from cust in customers  
            select new { Name = cust.Name, Address = cust.PrimaryAddress }; 

3. Is used to invoke default constructor.

int i = new int();
//equivalent to 
int i = 0;

Note:

  • Do not declare default constructor of struct because every type implicitly has a public default constructor.
  • It is possible to declare parameterized constructors on a struct type to set its initial values.
  • Types such as files handles, network connection it is recommended to use using statement to cleanup the resources.
  • New operator cannot be overloaded.

New Modifier

  • Hides a member that is inherited from a base class.
  • Derived version overrides the base class version.
  • You can hide without new keyword but with new modifier it suppressed the warning.
public class BaseC
{
	public it x;
	public void Invoke() {}
}

public class Derived : BaseC
{
	new public void Invoke() {}
}

Note:

  • Constants, fields, properties or type introduced in class or struct sharing the same name hides the base class members.
  • A method introduced in a class or struct hides properties, fields, and types that share that name in the base class.
  • An indexer introduced in a class or struct hides all base class indexers that have the same signature.
  • It is an error to use both new and override on the same member, because both have mutually same meaning. New creates new member, override extends the implementation.

New Constraints (Generic)

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.

To use the new constraint, the type cannot be abstract.

Apply the new constraint to a type parameter when your generic class creates new instances of the type, as shown in the following example:

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

When you use the new() constraint with other constraints, it must be specified last:

public class ItemFactory2
    where T : IComparable, new()
{
}

C# – Command Prompt

Using Visual Studio Command Prompt

Compiling files togehter
csc /t:exe /out:MyProgram.exe MyMainClass.cs MyClass.cs

or

csc /t:exe /out:MyProgram.exe *.cs

C# – List of Articles

List of Articles

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z