Important Points to Remember About C# Constructors
- Initialization: Constructors are used to initialize objects when they are created.
- No Return Type: Constructors do not have a return type, not even void.
- Same Name as Class: A constructor must have the same name as the class it belongs to.
- Default Constructor: If no constructor is defined, C# provides a default constructor.
- Parameterized Constructor: You can create constructors with parameters to initialize object properties with specific values.
- Constructor Overloading: C# allows multiple constructors with different parameters (constructor overloading).
- Access Modifiers: Constructors can have access modifiers (e.g., public, private) to control their accessibility.
- Invoked Automatically: Constructors are called automatically when an object is created using the new keyword.
- No Return Value: Unlike methods, constructors don’t return a value.
- Destructors: Destructors are used to clean up resources when an object is no longer needed, working alongside constructors.
Types of Constructor in C#
There are five different types of constructors in C#. They are:
Default Constructor
A default constructor takes no parameters. Every instance of the class is initialised to the same values by a default constructor. Within a class, the default constructor sets all numeric fields to zero and all string and object fields to null.
Example:
using System;
class DefaultConstructor {
// default constructor which is not parameterised
// i.e., there is nothing inside ()
public DefaultConstructor(){
Console.WriteLine("Inside the default constructor!");
}
// main method where the object is created
static void Main() {
// default constructor is automatically called when the object is created
DefaultConstructor cn= new DefaultConstructor();
}
}
Output:
Inside the default constructor!
Key points
- It does not have any parameters.
- Automatically called when an object is created.
- No return type.
Parameterized Constructor
A parameterized constructor is one that has at least one parameter. The benefit of a parameterized constructor is that each instance of the class can be initialised with a different value. Inside the constructor braces(), there should be at least one parameter.
Example:
using System;
class ParameterisedConstructor{
//data member which is not intialised currently
string company;
// Parameterised Constructor that takes a string value
// and initialises the company field
// we can also use "company" instead of "companyName" inside the braces
public ParameterisedConstructor(string companyName){
// using this operator we assign the value of companyName
// inside the current object's company field
this.company= companyName;
Console.WriteLine("Inside the Parameterised Constructor\n");
}
static void Main() {
// creating an object and passing a string value
ParameterisedConstructor obj= new ParameterisedConstructor("Coding Ninjas");
// using the object to print the data member's value
Console.WriteLine("I work at : " +obj.company);
}
}
Output:
Inside the Parameterised Constructor
I work at : Coding Ninjas
Key Points
- It should have at least one parameter.
- If we don't pass the value for the parameter while object creating it will throw a compile-time error.
- It has no return type.
Private Constructor
A private constructor is created using a private specifier. It is not possible for other classes to derive from this class, nor can an instance of this class be created. They are typically used in classes with only static members. If a class has one or more private constructors and no public constructor is present in the class, other classes (except nested classes) cannot create instances of this class.
Example:
using System;
class CodingNinjas {
// private constructor
private CodingNinjas(){
}
static void Main() {
// below line will give error
HelloWorld ob= new HelloWorld();
}
}
Output:
Compilation failed: 1 error(s), 0 warnings
Key Points
- Mostly used when we only have static members.
- It is an example of a singleton class pattern.
- If the constructor is made private, instances of the class cannot be created.
- No return type.
Static Constructor
When a constructor is created with the static keyword, it is invoked only once for all instances of the class, and it is invoked during the creation of the class's first instance or the first reference to a static member in the class. A static constructor is used to initialise the class's static fields and to write code that only needs to be executed once.
Example:
using System;
class CodingNinjas {
// create a static constructor using the static keyword
static CodingNinjas(){
Console.WriteLine("Inside a static constructor!");
}
// public parameterised constructor
public CodingNinjas(string name){
Console.WriteLine("I work at : "+name);
}
// main method for object creation
static void Main(){
// create an object of the CodingNinjas class
// observe that we do not leave the parameter empty.
// we pass "Coding Ninjas" as the string value
// It should have called only the second constructor
// but output also includes the message from the first constructor
CodingNinjas cn1= new CodingNinjas("Coding Ninjas");
// this object does not invoke the static constructor
// message inside the static constructor is not printed again
// static constructor is invoked only once.
CodingNinjas cn2= new CodingNinjas("Ninjas Coding");
}
}
Output:
Inside a static constructor!
I work at : Coding Ninjas
I work at : Ninjas Coding
Key Points
- It does not have access modifiers.
- It does not take any parameters.
- It cannot be called directly.
- It is invoked only once.
- No return type.
Copy Constructor
A copy constructor is a constructor that creates an object by copying variables from another object. A copy constructor's purpose is to initialise a new instance with the values of an existing instance.
Example:
using System;
class CodingNinjas {
// data members
string course;
string target;
// the instance constructor
public CodingNinjas(string course, string target){
this.course = course;
this.target = target;
}
// copy constructor
// It takes a reference of the CodingNinjas class
public CodingNinjas(CodingNinjas studentDetails){
course = studentDetails.course;
target = studentDetails.target;
}
// main method
static void Main(){
// first object cn1
CodingNinjas cn1 = new CodingNinjas("Data structures", "Interview preparation");
// second object cn2
// using copy constructor cn2 acquire the values from cn1
CodingNinjas cn2 = new CodingNinjas(cn1);
// use cn2 to print the values that were passed for cn1
Console.WriteLine(cn2.course);
Console.WriteLine(cn2.target);
}
}
Output:
Data structures
Interview preparation
Key Points
- It creates an object by copying variables from another object.
- Reference of the class is required as the parameter.
- No return type.
Properties of a Constructor
The key features or properties of a constructor are:
- They have the same name as that of the class.
- They do not have any return type, like methods.
- We cannot create more than one static constructor inside a class and the static constructor created cannot be parameterised.
- There is no restriction to the number of constructors that can be created.
- Access modifiers are not mandatory while creating a constructor.
Disadvantages of Constructors in C#
- Limited Flexibility: Constructors are fixed in terms of initialization. If you want to initialize an object with different values after creation, you may need to use additional methods or modify the constructor, which could complicate the code.
- No Return Value: Constructors cannot return any value, which limits their use when you need to provide feedback or status information about the object creation.
- Cannot be Inherited: Constructors cannot be inherited by derived classes. If you want to use a constructor in a subclass, you must explicitly call the base class constructor.
- Overloading Complexity: Overloading constructors with many parameters can make the code harder to understand and maintain, especially if there are too many variations to choose from.
- Resource Management: Constructors don’t always handle complex resource management well, such as when an object requires external resource allocation. This might lead to complicated logic in constructors.
Advantages of Constructors in C#
- Automatic Initialization: Constructors automatically initialize objects when they are created, reducing the need for separate initialization code.
- Control Over Object State: They allow you to enforce object state by ensuring certain properties are set when an object is created, which can prevent errors or undefined behavior.
- Code Readability: Using constructors helps make code more readable and structured, as it clearly defines how an object should be initialized.
- Support for Overloading: C# allows constructor overloading, meaning you can provide multiple constructors with different parameters to initialize objects in various ways.
- Object Setup in One Place: All setup logic is centralized in the constructor, ensuring that an object is ready for use immediately after creation without additional steps.
Frequently Asked Questions
Does C# need a constructor?
C# does not always need a constructor. If no constructor is defined, a default constructor is automatically provided by the compiler.
What is this () in constructor in C#?
The () in a constructor denotes a parameterless constructor. It’s used to initialize an object without requiring any arguments during object creation.
Why are constructors used?
Constructors are primarily used to initialise the data members (variables) of a class while creating an instance of the class.
How do you identify a constructor?
They are like methods having the same name as that of the class and no return type.
Also Read About - singleton design pattern in c#
Conclusion
In this article, we discussed various types of constructors in C# and their code implementation in C#.
- A constructor is a special method of a class that is automatically invoked when an instance of the class is created.
- They are like methods having the same name as that of the class and no return type.
- There are five different types of constructors in C#. They are default constructor, parameterised constructor, private constructor, static constructor, copy constructor.
We hope that this blog has helped you enhance your knowledge regarding constructors in C# and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!