A constructor is a special member function of a class. The constructor is executed when an object is created.

The default constructor does not have any parameters. However, you can create constructors with parameters. Such constructors are known as parameterized constructors.

Example – Default constructor

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Circle
{
//Declaring Member variables
public int radius;
public Circle() //Constructor
{
radius = 12;
}
//A member method
public void ShowData()
{
Console.WriteLine(radius);
Console.ReadKey();
}
}
class Program //The class
{
static void Main(string[] args) //Main method
{
Circle c = new Circle();
c.ShowData();
}
}
}

Output

12

Example 2 – Creating parameterized constructors

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Circle
{
//Declaring Member variables
public int radius;
public string color;
//Parameterized constructor
public Circle(int rad, string col)
{
radius = rad;
color = col;
}
//A member method
public void ShowData()
{
Console.WriteLine(radius);
Console.WriteLine(color);
Console.ReadKey();
}
}
class Program //The class
{
static void Main(string[] args) //Main method
{
Circle c = new Circle(10, "Red");
c.ShowData();
}
}
}

This program when executed will produce the following output.

10
Red

You can more than one constructor if their number of parameters are different.

Example

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Circle
{
//Declaring Member variables
public int radius;
public string name;

//First constructor
public Circle(int rad)
{
name = "Default";
radius = rad;
}
//Second constructor
public Circle(int rad, string _name)
{
name = _name;
radius = rad;
}
//A member method
public void ShowData()
{
Console.WriteLine("Name: " + name);
Console.WriteLine(radius);
}
}
class Program //The class
{
static void Main(string[] args) //Main method
{
Circle c = new Circle(10);
c.ShowData();
Circle c1 = new Circle(15, "Custom");
c1.ShowData();
Console.ReadKey();
}
}
}

Output

Name: Default
10
Name: Custom
15