C# Constructor

C# Constructor

23 May 2024
Advanced
1.02K Views
18 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

C# Constructor: An Overview

Constructors in C# serve as essential blueprints for object creation, initializing data members, and setting the stage for functionality. This article delves into the intricacies of C# constructors, exploring their types, best practices, and the pivotal role they play in object-oriented programming, guiding developers to build robust applications. In this C# Tutorial, we will explore more about Constructor in C#.

What is a Constructor in C#?

Constructor in C# is a special method with the same name as the class, used to initialize objects when they are created. It is automatically called when an object is instantiated, allowing initialization of class members and execution of specific logic before the object is used.

Syntax

 class Scholar{ 
 .......
 // Constructor
 public Scholar() {}
 .......
}

// An object is created of Scholar class,
// So above constructor is called

Important Points to Remember About Constructors in C#

  • A class's constructor must share the same name as the class it belongs to.
  • A constructor cannot be synchronized, final, or abstract.
  • There can be only one static constructor created per class.
  • There is no return type, not even void, for a constructor.
  • A parameterized constructor can't be a static constructor.
  • There can be any number of constructors in a class.
  • To limit access to a constructor, or which other class may call it, access modifiers can be used in the constructor declaration.

Read More - C# Interview Questions For Freshers

Types of Constructors in C#

There are 5 types of constructors in C#:

1. Default Constructor in C#

Default constructors are constructors that take no parameters. Every instance of the class must be initialized with identical values when using a default constructor. Inside a class, the default constructor sets all of the numeric values to zero and all of the string and object fields to null.

Example

Let's elaborate on this in C# Compiler.
 using System;
class Person
{
 // Properties
 public string Name { get; set; }
 public int Age { get; set; }

 // Default Constructor
 public Person()
 {
 Name = "John Doe";
 Age = 30;
 }
}

class Program
{
 static void Main()
 {
 // Creating an instance of the Person class using the default constructor
 Person person = new Person();

 // Printing the values
 Console.WriteLine("Name: " + person.Name);
 Console.WriteLine("Age: " + person.Age);
 }
}

Explanation

In this example, the Person class has a default constructor that initializes the Name property to "John Doe" and the Age property to 30. In the Main method of the Program class, an instance of the Person class is created using the default constructor, and then the name and age values are printed to the console.

Output

Name: John Doe
Age: 30

2. Parameterized Constructor in C#

A constructor is considered parameterized if it accepts at least one parameter. Each instance of the class may have a different initialization value.

Example

 // C# Program to illustrate calling of parameterized constructor.
using System;
namespace ParameterizedConstructorExample {

class Scholar {

// data members of the class.
String name;
int id;

// parameterized constructor would
// initialized data members with
// the values of passed arguments
// while object of that class created.
Scholar(String name, int id)
{
 this.name = name;
 this.id = id;
}

// Main Method
public static void Main()
{

 // This will invoke parameterized
 // constructor.
 Scholar scholar1 = new Scholar("DNT", 1);
 Console.WriteLine("ScholarName = " + scholar1.name +
 " and ScholarId = " + scholar1.id);
}
 }
}

Explanation

This C# code defines a Scholar class with a parameterized constructor. It creates an object scholar1, initializes its name and id, and then prints the values.

Output

ScholarName = DNT and ScholarId = 1

3. Copy Constructor in C#

By copying variables from another object, this constructor generates an object. Its primary function is to set a new instance's starting values to those of an existing instance.

Example

 // C# Program to illustrate calling a Copy constructor
// C# Program to illustrate calling a Copy constructor
 using System;
 
 namespace copyConstructorExample
 {
 class Scholars
 {
 private string month;
 private int year;
 
 // Declaring Copy constructor
 public Scholars(Scholars s)
 {
 month = s.month;
 year = s.year;
 }
 
 // Instance constructor
 public Scholars(string month, int year)
 {
 this.month = month;
 this.year = year;
 }
 
 // Get details of Scholars
 public string Details
 {
 get
 {
 return "Month: " + month.ToString() + "\nYear: " + year.ToString();
 }
 }
 
 // Main Method
 public static void Main()
 {
 // Create a new Scholars object.
 Scholars g1 = new Scholars("August", 2023);
 
 // here is g1 details is copied to g2.
 Scholars g2 = new Scholars(g1);
 
 Console.WriteLine(g2.Details);
 }
 }
 }
 

Explanation

This C# code in the C# Editor demonstrates a copy constructor in the Scholars class. It creates objects g1 and g2, where g2 is initialized using the copy constructor, displaying g1's details.

Output

Month: August
Year: 2023

4. Private Constructor in C#

A constructor is referred to as a private constructor if it was created with the private specifier. This class cannot be derived from by any other classes, nor can an instance of this class be created.

Example

 // A Private Constructor
using System;

 namespace privateConstructorExample
 {
 public class Scholars
 {
 // Declare a private constructor
 private Scholars()
 {
 }
 
 // Declare a static variable field
 public static int count_scholars;
 
 // Declare a static method
 public static int scholars_Count()
 {
 return ++count_scholars;
 }
 
 public static void Main()
 {
 // If you uncomment the following
 // statement, it will generate
 // an error because the constructor
 // is inaccessible:
 // Scholars s = new Scholars(); // Error
 
 Scholars.count_scholars = 199;
 
 // Accessing without any instance of the class
 Scholars.scholars_Count();
 
 Console.WriteLine(Scholars.count_scholars);
 
 // Accessing without any instance of the class
 Scholars.scholars_Count();
 
 Console.WriteLine(Scholars.count_scholars);
 }
 }
 }

Explanation

This C# code demonstrates a private constructor in the Scholars class, preventing object creation from outside the class. It uses a static method to access and modify a static variable.

Output

200
201

5. Static Constructor in C#

When the first reference to a static member of the class was created, the static constructor—which only has to be called once in the whole class—was called. Static constructors are designed to be used just once to initialize static class fields or data.

Example

 // A Static Constructor
using System;
namespace staticConstructorExample {
class scholars {

// It is invoked before the first
// instance constructor is run.
static scholars()
{

 // The following statement produces
 // the first line of output,
 // and the line occurs only once.
 Console.WriteLine("Static Constructor");
}

// Instance constructor.
public scholars(int i)
{
 Console.WriteLine("Instance Constructor " + i);
}
// Instance method.
public string scholars_detail(string name, int id)
{
 return "Name:" + name + " id:" + id;
}
// Main Method
public static void Main()
{

 // Here Both Static and instance
 // constructors are invoked for
 // first instance
 scholars obj = new scholars(1);
 Console.WriteLine(obj.scholars_detail("DNT", 1));
 // Here only instance constructor
 // will be invoked
 scholars obj1 = new scholars(2);
 Console.WriteLine(obj1.scholars_detail("DotNetTricks", 2));
}
}
}

Explanation

This C# code demonstrates static and instance constructors. The static constructor runs once before any instance is created. Instance constructors are called for each object instance created.

Output

Static Constructor
Instance Constructor 1
Name:DNT id:1
Instance Constructor 2
Name:DotNetTicks id:2
Conclusion

In conclusion, constructors in C# are essential components, initializing objects and ensuring proper program execution. Mastering constructors enhances code efficiency and readability, vital for any C# developer. Also, Consider our C# Programming Course for a better understanding of all C# concepts.

FAQs

Q1. What is a constructor for C#?

A constructor is a special method that is used to initialize objects. 

Q2. What is constructor and destructor in C#?

What are Constructors & Destructors? The constructor is a special method of the class that is called when a class is instantiated. A destructor is the opposite of a constructor

Q3. What is constructor used?

A constructor is used to construct an object and assign values to the object's members.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Azure DevOps Certification Training Course Jun 01 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Data Structures and Algorithms Training Jun 04 TUE, FRI
Filling Fast
08:30PM to 10:00PM (IST)
Get Details
ASP.NET Core Certification Training Jun 14 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 22 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this