Types of Constructors

 

Constructors are special methods in C# that are used to initialize  the objects of a class. They don't have a return type and have the same name as the class. Their primary purpose is to set the initial state of an object when it's created.

 

C# supports several types of constructors:

  • Default Constructor (Implicit or Explicit Parameterless)
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor
  • Private Constructor

 

 

Default Constructor (Parameterless, either Implicit or Explicit)

  • Implicit Default Constructor: 
    • A default constructor is one that doesn't take any arguments.
    • If you don't provide a constructor in your class, the C# compiler will automatically give you a public parameterless constructor. This is called a "implicit default constructor." 
    • This constructor sets all fields to their default values, such as 0 for numeric types, null for reference types, and false for bool.
  • Explicit Parameterless Constructor: I
    • f you want to do some specific initialisation logic when an object is created without any arguments, you can make your own parameterless constructor.

 

 

 

Parameterized Constructor
A parameterised constructor can take one or more parameters.  These parameters are used to initialize the object's fields with values passed during object creation. This allows you to create objects with specific initial states.

 

 

 

Constructor for Copying
A copy constructor is a unique constructor that constructs a new object by replicating the field values from an existing object of the same class. There is no built-in notion of a "copy constructor" in C#, unlike C++. However, you can implement one by defining a parameterised constructor that accepts an instance of its own class as a parameter.

 

 

 

Static Constructor
A static constructor is used to initialise static members of a class or to execute a specific action only once when the class is first loaded into memory.

Key attributes: The static keyword is employed to declare it.

  • It is incapable of accepting any parameters.
  • It is not permissible to include an access modifier (e.g., public, private).
  • It is invoked automatically prior to the creation of any class instance or the access of any static members.
  • Each class is limited to a single static constructor.


 


Private Constructor

 

A constructor with the private access modifier is referred to as a private constructor. It prevents the creation of instances of a class from outside the class itself. This is commonly used in two main scenarios:

  • Singleton Pattern: To guarantee that only one instance of a class can be created at any given time.
  • Utility Classes: For classes that consist solely of static members and methods (e.g., Math class), where it is not desired to create an instance of the class.

 

 

 

 

 

 


Related Question