What is a constructor in C#?

A constructor is a special method of the class that contains a collection of instructions and gets automatically invoked when an instance of the class is created.

In C#, a constructor is a special type of method that is automatically called when an instance of a class is created. It is used to initialize the newly created object. Constructors have the same name as the class and do not have a return type, not even void. They can be overloaded, meaning you can have multiple constructors with different parameter lists.

Here’s a breakdown of key points about constructors in C#:

  1. Initialization: Constructors are primarily used to initialize the state of an object, setting initial values for its fields or properties.
  2. Name: The name of the constructor must be the same as the name of the class.
  3. No Return Type: Constructors do not have a return type, not even void.
  4. Automatic Invocation: Constructors are automatically invoked when an instance of a class is created using the new keyword.
  5. Overloading: You can define multiple constructors for a class, allowing for different ways to initialize objects.

Example:

csharp
public class MyClass
{
private int myField;

// Default Constructor
public MyClass()
{
myField = 0; // Initialize fields
}

// Constructor with parameters
public MyClass(int initialValue)
{
myField = initialValue; // Initialize fields with parameter value
}
}

In this example, MyClass has two constructors: a default constructor that initializes myField to 0 and a parameterized constructor that allows initializing myField with a specified value.