Constructor

Whenever the object of a class is created, we explicitly call a constructor of that class.

Types of the constructor:

1. Default Constructor
2. Parameterized Constructor
3. Private Constructor
4. Static Constructor

1. Default Constructor:

Parameterless constructor can be defined explicitly by the program or will be defined implicitly when there is no constructor. This constructor helps to initialize all numeric variables to zero and object and string fields to null.

Example 1

 

using System;
namespace SampleProgram {
  class MySample {
    int xNum;
    MySample() {
      Console.WriteLine("Default Constructor");
    }
    public static void Main(string[] args) {
      // constructor called during obj created
      MySample obj = new MySample();
      Console.WriteLine($ "variable xNum value is {obj.xNum }");
    }
  }
}

 

The output will be:

Default Constructor
variable xNum value is 0

 

2. Parameterized Constructor:

The values to the parameters have to be sent while creating the object for a Parameterized Constructor.

Example 2

 

using System;
namespace SampleProgram {
  class MySample {
    int xNum;
    string info;
    MySample(int x, string y) {
      Console.WriteLine( "Parameterized Constructor");
      this.xNum = x;
      this.info = y;
    }
    public static void Main(string[] args) {
      // constructor called during obj created
      MySample obj = new MySample( "101",  "Hello World");
      Console.WriteLine($ "values are {obj.xNum} and  {obj.xNum} ");
    }
  }
}

 

The output will be:


Parameterized Constructor
values are 101 and Hello World

 

3. Private Constructor:

The constructor having the private access modifier is called a private constructor. This private constructor restricts the other classes to create an instance of the class where it is defined. So the private class cannot participate in inheritance.

Example 3

 

using System;
namespace SampleProgram {
  class MySample {
    int xNum;
    private MySample() {
      Console.WriteLine( "Private Constructor");
    }
    public static void Main(string[] args) {
      // gets a compile time error as constructor is not accessible.
      MySample obj = new MySample();
    }
  }
}

 

Compile error.

Gets the compile time error as the constructor is not accessible.

 

4. Static Constructor:

The constructor having the static access modifier is called a static constructor. This static constructor is invoked only once even though multiple instances are created and automatically called before any other type of constructor. This helps in instantiate any static data fields in the class.

Example 4

 

using System;
namespace SampleProgram {
  static class MySample {
    public static int discount;
    static MySample() {
      discount = 30;
    }
    public static void Main(string[] args) {
      Console.WriteLine($ "Discount is {MySample.discount}");
    }
  }
}

 

The output will be:

Discount is 30

 

Related Tutorials