A One-Stop Solution Guide to Understand Constructors in C#

Classes and objects are used in C# program design because of the language's emphasis on object-oriented concepts. In C #, it is a real-world object, like a chair, car, pen, mobile, or laptop. In other words, a "state and behavior" object. Data and functionality are referred to as "state" and "behavior". 

Runtime entities, like objects, are produced as needed. An object is a specific instance of a particular type of class. A class in C# is a collection of related objects. An object can be constructed from this template. Fields, methods, constructors, and so on can be included in this. The object provides access to all class members.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Are Constructors?

Constructor-in-C#-what-img1.

A constructor is a special class method that is called every time an instance of the class is made. A constructor, like a method, has a group of instructions that are run when an object is made. It is used to set the values for the data members of the same class at the start.

Types of C# Constructors

Constructor-in-C#-Types-img1

There are 5 Types of Constructors in C#, they are:

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

Now, you will explore each of them in detail.

Our Free Courses with Certificate

Introduction to C#Enroll Now
Introduction to Front End DevelopmentEnroll Now!
C Programming BasicsEnroll Now!
JavaScript for BeginnersEnroll Now!
Introduction to C++Enroll Now!

Default Constructor in C#

The term "default constructor" refers to a constructor that accepts no input arguments. Every class instance must be initialized to the identical values in a default constructor. The default constructor sets all numeric fields to zero and all string and object fields to null within a class.

Code:

// C# Program to demonstrate a Default constructor

using System;

namespace DefaultConstructor {

class DefConstruct {

int num;

string name;

// this would be invoked while the

// object of that class created.

DefConstruct()

{

Console.WriteLine("Constructor Called");

}

// Main Method

public static void Main()

{

// this would invoke default

// constructor.

DefConstruct def1 = new DefConstruct();

// Default constructor provides

// the default values to the

// int and object as 0, null

// Note:

// It Give Warning because

// Fields are not assign

Console.WriteLine(def1.name);

Console.WriteLine(def1.num);

}

    }

}

Constructor-in-C%23-defc-img1.

Parameterized Constructor in C#

The term parameterized constructor refers to a constructor with at least one parameter. It can set different values for each instance of the class.

Code:

//A C# Program to initialize parameterized constructor.

using System;

namespace ParameterizedConstructor {

class ParamConstruct {

//class data members

String comname;

int id;

//This class's parameterized constructor would 

//initialize data members with the values of passed arguments.

ParamConstruct(String comname, int id)

{

this.comname = comname;

this.id = id;

}

// Main() Method

public static void Main()

{

// This will initialize parameterized constructor.

ParamConstruct Param1 = new ParamConstruct("Simplilearn", 1);

Console.WriteLine("Welcome to " + Param1.comname +" and Parameter number = " + Param1.id);

}

  }

}

Constructor-in-C#-Parac-img1

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Copy Constructor in C#

By copying variables from another object, this constructor generates an object. Its primary purpose is to set the values of a new instance to those of an existing one.

Code:

// C# Program to illustrate Copy constructor

using System;

namespace copyConstructor {

class CpConstruct {

private string mnth;

private int yr;

// declaring Copy constructor

public CpConstruct(CpConstruct C)

{

mnth = C.mnth;

yr = C.yr;

}

// Instance constructor

public CpConstruct(string mnth, int yr)

{

this.mnth = mnth;

this.yr = yr;

}

// Get Info on CpConstruct

public string Info

{

get

{

return "Month: " + mnth.ToString() +

"\nYear: " + yr.ToString();

}

}

// Main Method

public static void Main()

{

// Create a new CpConstruct object.

CpConstruct C1 = new CpConstruct("May", 2022);

// here, C1 info is copied to C2.

CpConstruct C2 = new CpConstruct(C1);

Console.WriteLine(C2.Info);

}

  }

}

Constructor-in-C#-Copyc-img1

Private Constructor in C#

A private constructor is a constructor that is created with the private specifier. Other classes cannot inherit from this class, and it is also impossible to create an instance of this class.

Code: 

// C# Program to illustrate calling

// a Private constructor

using System;

namespace privateConstructor {

public class pvtConstruct {

// declare private Constructor

private pvtConstruct()

{

}

// declare static variable field

public static int count_pvtConstruct;

// declare static method

public static int pvtConstruct_Count()

{

return ++count_pvtConstruct;

}

// Main Method

public static void Main()

{

// If you uncomment the following

// statement, it will generate

// an error because the constructor

// is unaccessible:

// pvtConstruct p = new pvtConstruct(); // Error

pvtConstruct.count_pvtConstruct = 99;

// Accessing without any

// instance of the class

pvtConstruct.pvtConstruct_Count();

Console.WriteLine(pvtConstruct.count_pvtConstruct);

// Accessing without any

// instance of the class

pvtConstruct.pvtConstruct_Count();

Console.WriteLine(pvtConstruct.count_pvtConstruct);

}

    }

}

Constructor-in-C#-Pvtc-img1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Static Constructor in C#

This constructor is called just once in the class, and it is called when the first reference to a static member of the class is made, which is when the static constructor is called. A static constructor is used to initialize the class's static fields or data and is only used once.

Code:

//A C# Program to demonstrate a Static constructor

using System;

namespace staticConstructor {

class StConstruct {

// It is intialised before the first

// instance constructor is run.

static StConstruct()

{

// The following statement produces

// the first line of output,

// and the line occurs only once.

Console.WriteLine("Static Constructor");

}

// Instance constructor.

public StConstruct(int ins)

{

Console.WriteLine("Instance Constructor " + ins);

}

// Instance method.

public string StConstruct_detail(string comname, int comid)

{

return "Company Name:" + comname + "Company id:" + comid;

}

// Main Method

public static void Main()

{

// Here Both Static and instance

// constructors are invoked for

// first instance

StConstruct obj = new StConstruct(1);

Console.WriteLine(obj.StConstruct_detail("Simplilearn", 1));

// Here only instance constructor

// will be invoked

StConstruct obj1 = new StConstruct(2);

Console.WriteLine(obj1.StConstruct_detail("SimpliCode", 2));

}

  }

}

Constructor-in-C#-statc-img1

With this, you must have gained a good grip on the fundamentals of Constructors in C#. 

Next Steps

The next lesson in your C# training can be "Conditionals in C#." Conditional statements in C# are used when you wish to perform a certain action based on a given condition. Decision-making statements necessitate a few conditions that the program may assess and a set of statements that can be performed if the condition evaluates as true, or another statement that can be run if the condition evaluates as false.

Simplilearn is the world's most popular online Bootcamp for developing skills in the digital economy, and it's here to assist you in doing just that. Digital marketing and data science are just two topics we cover extensively in our online courses.

If you arelooking to enhance your software devlopment skills, we recommend you check Simplilearn's Full Stack Developer - MERN Stack. This program can help you hone the right skills and make you job-ready in no time.

The comments section below is open for questions and comments about this tutorial. Happy learning!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.