C# constructors are a fundamental part of object-oriented programming that play a critical role in object creation and initialization. In simple terms, a constructor is a method that is called automatically when an object is created. Its primary purpose is to initialize the object’s state and set its initial values.
Constructor Types
In C#, there are two types of constructors:
- Default
- Parameterized
Default Constructor
A default constructor is automatically created by the compiler if no constructor is explicitly defined, and it initializes the object with default values.
Here’s an example of a default constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Car { public string Make { get; set; } public string Model { get; set; } public int Year { get; set; } public Car() { Make = "Unknown"; Model = "Unknown"; Year = 0; } } |
In this example, we have a Car class with three properties: Make, Model, and Year. The default constructor initializes these properties with default values of “Unknown” and 0.
Parameterized Constructor
A parameterized constructor takes arguments and uses them to set initial values for the object’s properties.
Now let’s look at an example of a parameterized constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Car { public string Make { get; set; } public string Model { get; set; } public int Year { get; set; } public Car(string make, string model, int year) { Make = make; Model = model; Year = year; } } |
In this example, we have a Car class with the same three properties, but this time, we have a parameterized constructor that takes arguments for each property. When we create an instance of the Car class using this constructor, we can pass in values to initialize the properties.
1 |
Car myCar = new Car("Toyota", "Camry", 2022); |
Here, we’ve created a new Car object with a Make of “Toyota”, a Model of “Camry”, and a Year of 2022. By the way, did you know that we offer a unique online course that boosts your C# career? Check it out here!
Encapsulation
Constructors are also useful for encapsulating objects. Encapsulation is a fundamental principle of object-oriented programming, when we encapsulate objects we make them easier to use by hiding their internal complexity from the object’s clients. When encapsulating objects, constructors ensure that the object is always created in a valid state. Encapsulation allows us to control how an object is accessed and manipulated by restricting direct access to its internal complexity. By encapsulating an object’s state, we can protect it from external interference and ensure that it remains consistent and valid. This helps to prevent bugs and errors caused by accidental modification of an object’s state.
Look at this example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class BankAccount { public string AccountNumber { get; private set; } public decimal Balance { get; private set; } public BankAccount(string accountNumber, decimal initialDeposit) { AccountNumber = accountNumber; if (initialDeposit < 100) throw new InvalidOperationException("Insufficient initial deposit"); Balance = initialDeposit; } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { if (Balance < amount) throw new InvalidOperationException("Insufficient funds"); Balance -= amount; } } |
In this example, we have a BankAccount
class that has an AccountNumber
and a Balance property. We’ve defined a parameterized constructor that takes an account number and an initial deposit amount. We’ve also defined two methods for depositing and withdrawing funds from the account.
By encapsulating the initial deposit within the constructor, we ensure that the BankAccount
object is always created in a valid state. We can’t create a BankAccount
object without specifying an account number and an initial deposit, so we prevent the creation of invalid accounts. likewise we can’t create BankAccounts
with invalid initial deposits.
Encapsulation also allows us to change the internal implementation of an object without affecting the rest of the system. As long as the object’s interface remains the same, other objects that depend on it can continue to use it without any modifications. With constructors, we can also ensure that objects are created with consistent values across multiple instances. For example, if we have a class that represents a currency, we can use a parameterized constructor to ensure that each currency object is always created with the same decimal places and rounding rules.
Conclusion
In conclusion, C# constructors are a critical component of object-oriented programming that allow us to create and initialize objects. They can be used to encapsulate an object’s state and ensure that objects are always created in a valid state. C# constructors allow us to ensure that objects are always created in a valid state, encapsulate an object’s state, and ensure consistency across multiple instances. Constructors can play an important role in producing robust, reliable, and maintainable object-oriented code. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development.