CSharp/C# Tutorial - C# Constructors

Instance Constructors

Constructors run initialization code on a class or struct.

A constructor is defined like a method.

The constructor has the same name with type and has no return type:

public class Person {
   string name; // Define field
   public Person (string n){ // Define constructor
      name = n;              // Initialization code
Person p = new Person ("CSS"); // Call constructor 

Instance constructors allow the following modifiers:

Access modifierspublic internal private protected
Unmanaged code modifiersunsafe extern

Overloading constructors

A class or struct may overload constructors.

To avoid code duplication, one constructor may call another, using the this keyword:

using System; //from  w  ww  . j a  v a2 s .co  m

public class Product {
   public decimal Price;
   public int Year;
   public Product (decimal price) { 
      Price = price; 
   public Product (decimal price, int year) : this (price) { 
     Year = year; 

When one constructor calls another, the called constructor executes first.

We can pass an expression into another constructor as follows:

public Product (decimal price, DateTime year) : this (price, year.Year) { 

The expression itself cannot make use of the this reference.

Implicit parameterless constructors

For classes, the C# compiler automatically generates a parameterless public constructor if and only if we do not define any constructors.

For structs, a parameterless constructor is intrinsic to the struct; therefore, we cannot define our own.

Constructor and field initialization order

We saw previously that fields can be initialized with default values in their declaration:

class Sprite {
   int shields = 50; // Initialized first
   int health = 100; // Initialized second 

Field initializations occur before the constructor is executed, and in the declaration order of the fields.

Nonpublic constructors

Constructors do not need to be public.

A common reason to have a nonpublic constructor is to control instance creation via a static method call.

public class Class1 { 
    Class1() {} // Private constructor 
    public static Class1 Create (...) {
       // call Class1 constructor here

Static Constructors

A static constructor executes once per type, not once per instance.

A type can define only one static constructor, and it must be parameterless and have the same name as the type:

class Main {
    static Main () { 
       Console.WriteLine ("Type Initialized"); 

The runtime automatically invokes a static constructor just prior to the type being used.

Two things trigger this:

  • Instantiating the type
  • Accessing a static member in the type

The only modifiers allowed by static constructors are unsafe and extern.

Static field initializers run just before the static constructor is called.