Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Introduction to Constructors in C#

Constructors are methods in C# that initialise all the objects or class data members. They are automatically called whenever a class object is created. In case there are no absolutely defined constructors in the class, the compiler automatically creates a default constructor. You can use it to set initial values for fields. 

In other words, a constructor gets executed automatically whenever you create or instantiate an object of the particular class having a constructor. Similar to methods, a constructor in C# also incorporates the collection of instructions that execute during object creation. It helps you to assign the initial values to the objects of the same class.

Let’s dive in to explore a lot more about constructors in C!

Check out our Technology free courses to get an edge over the competition.

Basic Syntax of Constructors in C#

After understanding what is constructor in C, let’s look at its syntax.

class Student {

// Constructor

public Student() {

// constructor code goes here

}

// other class members go here

}

// The below command calls the above constructor after creating an object of the Student class

Student obj = new Student();

Constructor Overloading in C#

Whenever multiple constructors with the same name are defined within the same class, it is known as constructor overloading. The condition is that the parameters are unique for each C# constructor.

Let’s look at a C# constructor example.

public class Student {

private double English;

private double Science;

private double Physics;

private string StudentName;

//Shows the result of two students in various subjects.

Student a1 = new Student();

Student a2 = new Student(“Mark”, 75, 90);

The above example shows the result of two students in three subjects. To demonstrate the working of constructor overloading, the name is displayed for the second student only.

Here’s how it looks running the following code.

using System;

namespace StudentNamespace

{

public class Student

{

private double English;

private double Science;

private double Physics;

private string StudentName;

// Default constructor

public Student()

{

English = 0;

Science = 0;

Physics = 0;

StudentName = “Unknown”;

}

// Constructor with name parameter

public Student(string name)

{

English = 0;

Science = 0;

Physics = 0;

StudentName = name;

}

// Constructor with name, English, and Science grades parameters

public Student(string name, double english, double science)

{

English = english;

Science = science;

Physics = 0;

StudentName = name;

}

public void DisplayStudentInfo()

{

Console.WriteLine(“Student Name: ” + StudentName);

Console.WriteLine(“English Grade: ” + English);

Console.WriteLine(“Science Grade: ” + Science);

Console.WriteLine(“Physics Grade: ” + Physics);

Console.WriteLine();

}

}

class Program

{

static void Main(string[] args)

{

Student a1 = new Student(); // Using the default constructor

Student a2 = new Student(“Mark”); // Using the constructor with name parameter

Student a3 = new Student(“Mark”, 75, 90); // Using the constructor with name, English, and Science grades parameters
 
a1.DisplayStudentInfo();

a2.DisplayStudentInfo();

a3.DisplayStudentInfo();

}

}

}

Default Constructors in C#

A default constructor in C# accepts no arguments. If you don’t define a constructor in a class, C# automatically creates a default constructor (with no parameters and an empty code).

Every object of the class is initialised with the default values, which are defined in the default constructor. Hence, using this C# class constructor allows you to initialise diverse objects with diverse values.

Parameterized Constructors in C#

A parameterised constructor C# can accept one or multiple parameters. Hence, it can initialise different values to different class objects. 

Here’s an example program demonstrating a parameterised constructor:

using System;

namespace SampleParameterizedConstructor

{

class Sum

{

private int c;

private int d;

public Sum(int a, int b)

{

c = a;

d = b;

}

public int getSum()

{

return c + d;

}

}

class Result

{

static void Main(string[] args)

{

Sum s = new Sum(11,6);

Console.WriteLine(“Sum: {0}” , s.getSum());

}

}

}

The output is:

Sum: 17

Copy Constructors in C#

This constructor C# initialises the object values after copying the data from another object. It creates a new object that is a copy of the old object. 

Here is an example program for copy constructor in C#:

using System;

namespace SampleCopyConstructor

{

class Sum

{

private int c;

private int d;

public Sum(int a, int b)

{

c = a;

d = b;

}

public Sum(Sum s)

{

c = s.c;

d = s.d;

}

public int GetSum()

{

return c + d;

}

}

class Result

{

static void Main(string[] args)

{

Sum s1 = new Sum(1, 8);

Sum s2 = new Sum(s1);

Console.WriteLine(“Sum of 1 & 8: {0}”, s2.GetSum());

}

}

}

Output:

Sum of 1 & 8: 9

Check Out upGrad’s Software Development Courses to upskill yourself.

Static Constructors in C#

This C sharp constructor initialises any static data or completes a specific action that must be performed only once. C# automatically calls it before creating the first instance or referencing static members.

Here’s an example program demonstrating the use of a static constructor:

using System;

public class Account

{

public int employeeid;

public String employeename;

public static float performancescore;

public Account(int employeeid, String employeename)

{

this. employeeid = employeeid;

this. employeename = employeename;

}

static Account()

{

performancescore = 8.5f;

}

public void display()

{

Console.WriteLine(employeeid + ” ” + employeename+” “+performancescore);

}

}

class EmployeePerformance{

public static void Main(string[] args)

{

Account x1 = new Account(01, “James”);

Account x2 = new Account(02, “John”);

x1.display();

x2.display();

}

}

Output:

1 James 8.5

2 John 8.5

The above program displays the employee’s performance score for each employee.

Private Constructors in C#

You can create a private C sharp constructor by using the private access specifier. After creating a private constructor, you can’t create objects of the particular class in other classes. class NLog

{
private NLog() { }
public static double e = Math.E;
}

As seen from the above program, private constructors avoid creating instances of a class whenever there are no instance methods or fields.

Constructor Chaining in C#

In Constructor Chaining, a constructor calls another constructor in the same/base class.

public class NewClass

{

    public string bookName;

    public NewClass() : this(“XYZ Book”)

    {

    }

    public NewClass(string bookname)

    {

        bookName = bookname;

    }

}

class Namedisplay

{

    static void Main(string[] args)

    {

        NewClass nw = new NewClass();

        Console.WriteLine(nw.bookName);

    }

}

In the above example, two constructors are created. Calling the default constructor calls a parameterised constructor and assigns value to the variable. Next, we create the class’ object, call the default constructor, and output the value of the variable. Hence, the constructor is called another constructor, which demonstrates Constructor Chaining.

Object Initialisation in C#

Knowing what is constructor in C is inadequate because you must also know how to initialise an object. Object initialisers allow you to assign values to any accessible properties/fields of an object during the object’s creation. It doesn’t call a constructor.

Constructor vs Method in C#

Constructor

Method

A constructor is a special method used to initialise objects. A method is a group of statements that perform a task.
It is called when a class object is created. It helps you to initialise values for objects. Each C# program contains a minimum class with a method named Main.

It reduces the amount of code.

 

It makes a program more manageable by reusing the code.
The name of the class and constructor are always identical. You can use any name for the method.
It doesn’t have a return type. It has a return type.

Best Practices for Writing Constructors in C#

  • A constructor must have limited parameters.
  • You must be careful when adding a parameterised constructor to a class that doesn’t have it. If you do it, it prevents the C# compiler from adding the automatic parameterless constructor. This can lead to breaking changes in certain scenarios.
  • You can use a private constructor when you don’t want other classes to instantiate your classes.
  • Carefully use application logic in constructors. Aim to minimise redundant database operations in constructors (for example, loading a dataset that is used only in certain sections).

Real-World Examples of Constructors in C#

Here’s a real-world C# constructor example that better explains how it works.

Suppose you went to a shop to buy a pen. There can be several options for you to buy a pen.

The first alternative – You ask a shopkeeper to give you a pen. Since you didn’t specify the brand name and the pen type, the shopkeeper would provide you with the most commonly sold pen. This is a real-world example of a default constructor.

The second alternative – You ask a shopkeeper to provide you with a black pen from the XYZ brand. The shopkeeper will then provide you with the specific pen. In this instance, the parameters are set. This is a real-world example of the parameterised constructor.

The third alternative – You ask a shopkeeper to provide you with a pen that looks like the one you carried in your hand. The shopkeeper notices that pen and provides you accordingly. So, this example makes a copy of that marker. So, this alternative is a real-world example of copy constructor.

Conclusion

Constructors are crucial in C# since they offer a dependable and consistent method for initialising objects, guaranteeing that they are in a valid state when utilised. Developers can write well-organised, simple-to-maintain code by comprehending and properly utilising constructors.

We anticipate our blog will strengthen your knowledge of constructors in C# and how to use it effectively. Along with referring to this blog, mastering your technical skills is another vital facet that aspirants must discover, and this is what upGrad fosters!

One of the outstanding courses to realise your career development in the tech field is upGrad’s Full Stack Software Development Bootcamp. With exceptional facets like 100+ hours of learning, 20+ projects and case studies, real-life projects, 16+ hours of group career coaching, and more, upGrad can significantly assist your career development in the flourishing field of STEM!

Frequently Asked Questions (FAQs)

1. Can you define a method with the same class name in C#?

2. Do abstract classes have constructors in C#?

3. Can you override the constructor in C#?

Keerthi Shivakumar

230 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

Suggested Blogs