Constructors in C# [With Examples]
Updated on Jun 06, 2023 | 8 min read | 5.5k views
Share:
For working professionals
For fresh graduates
More
Updated on Jun 06, 2023 | 8 min read | 5.5k views
Share:
Table of Contents
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.
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();
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();
}
}
}
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.
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
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.
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.
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.
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.
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 |
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. |
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.
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!
Get Free Consultation
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
Top Resources