What Is a Constructor?
A constructor is a special method that gets called when an object of a class is created. It's used to initialize the object's fields and properties with default or user-specified values.
Constructors have the same name as the class they belong to and do not have any return type, not even void. They can take parameters, which are used to provide initial values for the object's fields and properties. If a class doesn't define a constructor explicitly, C# provides a default constructor that takes no parameters and initializes all fields to their default values.
What Are the Different Types of Constructors?
Default and Parameterless Constructors
Parameterized Constructors
Private Constructors
Static Constructors
Copy Constructors
Default or Parameterless Constructor
A default constructor is a constructor that takes no parameters, and it is automatically provided by the compiler if a class does not have any constructor defined. The default constructor initializes all the class fields to their default values, which means it initializes the reference type fields to null and the value type fields to their default values (0 for numeric types, false for boolean, etc)
public class MyClass
{
public int MyProperty { get; set; }
public MyClass()
{
Console.WriteLine("Default or Parameteless constructor Called");
}
}
using System;
class Program
{
static void Main(string[] args)
{
MyClass Obj = new MyClass()
Console.WriteLine("Hello, world!");
}
}
Output:
Default or Parameteless constructor Called
Hello, world!
Parameterized Constructor
A parameterized constructor is a constructor that takes one or more parameters, and it is used to initialize the object's fields and properties with values provided by the caller. Here is an example of how to write a parameterized constructor
using System;
class MyClass
{
public string Name {get; set; }
public int Age {get; set; }
public MyClass(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
using System;
class Program
{
static void Main(string[] args)
{
MyClass Obj = new MyClass("Rahat", 22)
Console.WriteLine($"Hello, My name is {obj.Name}
I am {obj.Age}.")
}
}
Output:
Hello, My name is Rahat. I am 22.
Private Constructor
A private constructor is a special type of constructor that can only be accessed within the same class in which it is defined. Private constructors are typically used to restrict the creation of objects of a class to within the class itself or within certain methods or properties of the class.
public class MyClass
{
public int Id { get; set; }
private MyClass()
{
}
public static MyClass CreateInstance()
{
return new MyClass();
}
}
using System;
class Program
{
static void Main(string[] args)
{
var obj = MyClass.CreateInstance();
obj.Id = 9;
Console.WriteLine(obj.Id);
}
}
Output:
9
One common use case for private constructors is in implementing the Singleton design pattern, where a class is designed to have only one instance throughout the lifetime of an application. By making the constructor private, the Singleton class can control the creation of its own instances and ensure that only one instance exists at any given time.
When we say "only one instance exists at any given time," it means that only one object of a particular class can be created and used throughout the lifetime of an application.
For example, let's say we have a Logger class that is responsible for logging messages to a file. We might want to ensure that only one instance of the Logger class exists at any given time so that all messages are written to the same log file.
To implement this, we can use the Singleton design pattern and create a private constructor that restricts the creation of new instances of the Logger class. Instead, we can create a static method that returns the single instance of the Logger class, and use that instance to write all log messages. This way, we can ensure that all log messages are written to the same file, regardless of how many times the Logger class is used in different parts of the application.
public class Logger
{
private static Logger instance = null;
private static readonly object padlock = new object();
private Logger()
{
// Private constructor code
}
public static Logger GetInstance()
{
lock (padlock)
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
Logger logger = Logger.GetInstance();
logger.Log("This is a log message");
Output:
This is a log message
Static Constructor
A static constructor is a special method that is automatically called by the runtime when the class is first accessed before any static members are accessed or any instance of the class is created.
The purpose of a static constructor is to initialize any static data or to perform any other static initialization that needs to be done before the class can be used. Static constructors are called only once per class, regardless of the number of instances of the class that are created.
A static constructor is declared using the Static keyword, and its name must be the same as the class name
public class MyClass
{
private static int studentCount;
static MyClass()
{
studentCount = -1;
}
}
A static constructor doesn’t take access modifiers or have parameters
A class can only have one static constructor
We cannot invoke a static constructor through code. A CLR invokes a static constructor automatically
If we don’t provide a static constructor to initialize static fields, all static fields are initialized to their default value as listed in the default values of C# types
Copy Constructor
A copy constructor is a constructor that takes an instance of its class as an argument. We use a copy constructor when we want to clone an object.
public class Person
{
public string Name {get; set; }
public int Age {get; set; }
public Person(Person student)
{
Name = student.Name;
Age = student.Age;
}
public void Display()
{
Console.WriteLine(Name + " " + Age);
}
}
using System;
class Program
{
var person2 = new Person("John Wick");
var copyPerson = new Person(person2);
copyPerson.Display();
}
John Wick 0