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