Last Updated on April 10, 2024 by Aram
Constructors in C# are an essential and core concept and functionality when writing code in the object-oriented approach.
They help you instantiate and build your objects in the way you decide how it will control the object creation.
A constructor is represented as a method that gets called whenever you instantiate an object from a class.
There are also special types of constructors that have their own rules and use cases.
In this article we will learn about the 6 types of constructors in C#.
Note that there is an example on each type of the constructor, I am not showing the output for you so that you can take the code example here and try it yourself and see the output.
So let’s get started.
Default Constructor
It is commonly known as the parameterless constructor or the instance constructor.
This constructor is called when creating a new instance of the class.
A default constructor would initialize the fields to their default values:
- Zero for numeric types
- null for reference types
You can override the default behavior by including your own initialization code within the default constructor.
1 2 3 4 5 6 7 8 |
public class QuestionModel { public QuestionModel() { Console.WriteLine($"Inside the default constructor"); } // Code removed for brevity } |
Parametrized Constructor
This is similar to the default constructor, and shares one of the names – instance constructor.
The difference is that it takes input from outside the class
Also you can define multiple overloads of the parametrized constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class QuestionModel { public int Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public bool IsActive { get; set; } public DateTime PostingDate { get; set; } public QuestionModel(string title, string description) { Title = title; Description = description; Console.WriteLine("Inside the first parametrized constructor"); } public QuestionModel(int id, string title, string description) { Id = id; Title = title; Description = description; IsActive = true; PostingDate = DateTime.Now; Console.WriteLine("Inside the second parametrized constructor"); } // Code removed for brevity } |
Private Constructor
It is a special constructor marked as private, so it is inaccessible from outside the class
If the class doesn’t have a parametrized constructor, creating a new instance from the class with private constructor throws an exception.
A private constructor can be used only with static members within the class.
Also a private constructor restricts a class from being inherited.
Some popular implementations for private constructors are through Singletons and Factories
The below is a simple form of singleton, please note that this is only to showcase the usage of private constructor is not intended to give the best implementation of Singletons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class SimpleSingleton { private static SimpleSingleton instance; private SimpleSingleton() { } public static SimpleSingleton GetInstance() { if (instance == null) { instance = new SimpleSingleton(); } return instance; } public void DoSomething() { Console.WriteLine("Inside Singleton Method"); } } |
Static Constructor
Used to initialize static members of a class/struct.
A static constructor is called before the instance constructor.
This type of constructor is automatically called before the creation of the instance, or when any static member is referenced.
The static constructor is called at most once even if multiple instances of the same class are created.
This is mainly used to define a global value for a class and use that value in any subsequent instance.
Can be useful to define some configurations for the type.
More rules on the static constructors:
- You cannot overload static constructor
- You cannot inherit a static constructor
- You cannot access a non-static field within a static constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class QuestionModel { static DateTime threadCreationTime; static short charactersLimit; static QuestionModel() { threadCreationTime = DateTime.Now; charactersLimit = 1000; Console.WriteLine("Inside the static constructor"); Console.WriteLine($"Setting the threadCreationTime"); Console.WriteLine($"Setting the charactersLimit \n"); } public QuestionModel() { Console.WriteLine("New instance created, default constructor"); Console.WriteLine($"threadCreationTime is {threadCreationTime}"); Console.WriteLine($"characters limit is {charactersLimit} \n"); } } // Invocation QuestionModel? question1 = new(); QuestionModel? question2 = new(); |
Copy Constructor
This type of constructor was first introduced in C++.
It is used to copy class members’ values to another class as to create a duplicate or clone.
Copying data from instance to instance requires you decide the depth level of copy in your copy constructor – Shallow and Deep.
Shallow copy copies values of the primitive data types and copies references of the reference types. Deep copy copies each of the primitive data types and creates new instance of the reference types and includes any nested reference types recursively.
A copy constructor should include an instance of the class as parameter.
And then inside it, you can manually assign each value from the input parameter instance to the matching member within the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public QuestionModel(QuestionModel questionModel) { Id = questionModel.Id; Title = questionModel.Title; Description = questionModel.Description; IsActive = questionModel.IsActive; PostingDate = questionModel.PostingDate; } QuestionModel question1 = new( 1, "How many words in English?", "This is the question, " + "how many words are there " + "in the English language?"); QuestionModel question2 = new QuestionModel(question1); Console.WriteLine($"Question Model 2 is {question2.Title}"); |
Primary Constructor
This was introduced in C# 12.
A primary constructor is a concise way to write parametrized constructor.
This constructor’s parameters have class or struct level scope.
You can use them to perform different operations:
- Initialize Properties or Fields
- Initialize base class
- Specify Parameters in Dependency Injection: Useful with ASP.NET Core Controllers when you are injecting dependencies in controllers or services
Important to note that the primary constructor’s parameter is only treated as a parameter not a field of a class or struct. So all rules of method parameters are also applied to the primary constructor’s parameters.
1 2 3 4 5 6 7 8 |
public class QuestionModel(int id, string title, string description) { public int Id => id; public string? Title => title; public string? Description => description; public bool IsActive => true; public DateTime PostingDate => DateTime.Now; } |
References
You can always read the official docs to learn more about the constructors in C#.
Check the following links:
Constructors (C# programming guide)
Using Constructors (C# Programming Guide)
Let me know in the comments what are your thoughts.
Did you see the concept of not showing the output and letting you try it a better way to learn and understand the topic?
Bonus
Enjoy the ethereal tunes of cello being played by one of the greatest Cello players – Yo yo ma.
A masterpiece by J.S. Bach:
Yo-Yo Ma – Bach: Cello Suite No. 1 in G Major, Prélude (Official Video)