C# Constructors
C# Constructors
A constructor in C# is a special method that is automatically called when an object is created.
It is used to initialize fields or perform setup tasks.
🔹 Key Features of Constructors
-
Same name as class
-
No return type (not even void)
-
Called automatically
-
Can be parameterized or default
🔹 Default Constructor
🔹 Parameterized Constructor
🔹 Constructor Overloading
You can have multiple constructors with different parameters.
🔹 Static Constructor
-
Called once when the class is first accessed
-
Used to initialize static members
🔹 Private Constructor
-
Used in Singleton design pattern
-
Prevents creation of objects outside the class
🔹 Common Mistakes
❌ Using a return type (constructors never have return types)
❌ Forgetting parameterized constructor call
❌ Confusing static and instance constructors
🔹 Summary
✔ Constructors initialize objects automatically
✔ Can be default, parameterized, or static
✔ Supports overloading
✔ Private constructors are used in special patterns
