- Author

- Name
- Nelson Silva
- Social
Introduction
Constructors play a fundamental role in object-oriented programming in C#. They allow us to initialise an object at the moment of its creation, ensuring that the object begins its lifecycle in a valid state.
- What are Constructors?
- Key Characteristics of Constructors
- Types of Constructors in C#
- Private Constructors and Constructor Chaining
- Code Example with Multiple Constructors
What are Constructors?
Constructors are special methods that are called at the moment an object is created. They are used to initialise the state of an object with specific values and ensure that the object is ready for use immediately after its creation.
Key Characteristics of Constructors
- Same Name as the Class: The name of a constructor must be exactly the same as the class.
- No Return Type: Constructors have no declared return type, not even
void. - Constructor Overloading: A class can have more than one constructor, each with different parameters.
Types of Constructors in C#
- Default Constructor: A constructor with no parameters. If no constructor is defined, C# automatically generates a default constructor.
- Parameterised Constructor: Accepts parameters, allowing an object to be initialised with specific values.
- Static Constructor: Executed once to initialise static members of the class.
Private Constructors and Constructor Chaining
- Private Constructors: Used in design patterns such as Singleton. They prevent instances of the class from being created outside the class itself.
- Constructor Chaining: Allows a constructor to call another in the same class using
: this(). This helps avoid code duplication.
Code Example with Multiple Constructors
Let's look at an example that illustrates the different types of constructors:
namespace Base {
class Person {
public string Name { get; set; }
public int Age { get; set; }
// Default constructor
public Person() {
Name = "Unknown";
}
// Parameterized constructor
public Person(string name) {
Name = name;
}
// Constructor chaining
public Person(string name, int age) : this(name) {
Age = age;
}
}
}
Conclusion
Constructors are fundamental in object-oriented programming. They not only set up an object for immediate use, but also help maintain data integrity and promote safe programming practices.