Facebook Page Twitter Page LinkedIn Page
× C# Tutorial C# Advanced C# Resources


A constructor is a special method of a class which automatically executed when a new object of the class is created. It allows the class to initialize member fields and allocate memory.

The constructor function is declared just like a regular member method except the class name and method name should be same without any return type.

When a constructor is not specified in a class, compiler generates a default constructor and inserts it into the code. However, it does not initialize member fields.

Syntax

//Creating class constructor
class_name(parameters) {
  statements;
}

Example:

In the below example, a class called Circle is created. A constructor is also created which is used to initialize the member field radius.

using System;

class Circle {
  //class member field
  int radius;
  //class constructor
  public Circle(int x) {
    radius = x;
  }
  //class method
  public double area() {
    return 22/7.0*radius*radius;
  }

  static void Main(string[] args) {
    Circle Cir1 = new Circle(5);
    Circle Cir2 = new Circle(10);

    Console.WriteLine(Cir1.area());
    Console.WriteLine(Cir2.area());
  }
}

The output of the above code will be:

78.5714285714286
314.285714285714

Constructor Overloading

Like Methods, a constructors can also be overloaded in C#. With constructor overloading feature in C#, two or more constructors can be created in the same class with different definitions - different number of parameters and/or different types of parameters. The compiler automatically calls the constructor which matches the argument passed while creating the object.

Example:

In this example two constructors are created. The first constructor (default constructor) takes no parameters and the second constructor takes one parameter to initialize an object of the class Circle.

In the main method, two objects of class Circle are created: Cir1 and Cir2. Cir1 uses default constructor to initialize the object while the Cir2 uses the constructor that takes one parameter to initialize the object.

using System;

class Circle {
  //class member field
  int radius;
  //class constructor without parameter
  public Circle() {
    radius = 1;
  }  
  //class constructor with one parameter
  public Circle(int x) {
    radius = x;
  }
  //class method
  public double area() {
    return 22/7.0*radius*radius;
  }

  static void Main(string[] args) {
    Circle Cir1 = new Circle();
    Circle Cir2 = new Circle(10);

    Console.WriteLine(Cir1.area());
    Console.WriteLine(Cir2.area());
  }
}

The output of the above code will be:

3.14285714285714
314.285714285714

A constructor is called default constructor, if it takes no arguments to initialize the object.


5