Programs

Constructors in C# [With Examples]

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.

Explore our Popular Software Engineering Courses

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).

In-Demand Software Development Skills

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!

Enrol now to begin your journey!

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

No, in C#, if you define a method with the same class name, it will show a compile-time error.

Do abstract classes have constructors in C#?

Abstract classes are types of classes, so they can have constructors to initialise properties. Although we can’t instantiate an abstract class, we can use constructor chaining to call the abstract class’ constructor.

Can you override the constructor in C#?

You can't override constructors because constructors aren't called polymorphically. You always specify which class you want to construct and the arguments for the particular constructor.

Want to share this article?

Leave a comment

Your email address will not be published. Required fields are marked *

Our Trending Cloud Computing Courses

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks