C sharp - Constructor in C#
A constructor is a special method in a class that is automatically invoked when an object of the class is created. It is used to initialize objects.
Syntax
class ClassName
{
public ClassName()
{
// Initialization code
}
}
-
The constructor name must match the class name.
-
It has no return type, not even
void
.
Types of Constructors in C#
1. Default Constructor
-
Takes no parameters.
-
Automatically provided if no constructor is defined explicitly.
2. Parameterized Constructor
-
Accepts arguments to initialize object fields with specific values.
3. Copy Constructor
-
Used to create a new object by copying values from an existing object of the same class.
4. Static Constructor
-
Initializes static data members.
-
Executes only once, when the class is first accessed.
-
Cannot take parameters.
5. Private Constructor
-
Used to restrict object creation from outside the class.
-
Commonly used in Singleton patterns.