A constructor is a special method in Object-Oriented Programming (OOP) that is automatically called when an object is created. It is used to initialize the object's properties and ensure the object starts in a valid state.
In C#, a constructor has the same name as the class and does not return any value.
class BankAccount { private double balance; private string owner; // Constructor public BankAccount(string owner, double initialBalance) { this.owner = owner; balance = initialBalance > 0 ? initialBalance : 0; Console.WriteLine($"Account created for {owner} with balance {balance}"); } public void Deposit(double amount) { if (amount > 0) { balance += amount; Console.WriteLine($"Deposited: {amount}"); } } public double GetBalance() { return balance; } } var account = new BankAccount("John Doe", 1000); account.Deposit(500); Console.WriteLine($"Current Balance: {account.GetBalance()}");
BankAccount
owner
balance
0
Constructors help ensure that objects are always in a valid state when they are created. They improve code structure, prevent errors, and enhance maintainability.
In the next articles, we will explore other Object-Oriented Programming principles such as Inheritance and Abstraction using a consistent example structure.
I am Ready to Make Your Project Process Happy.
For Your Great Business Idea; Together, We Can Create a Perfect Solution.
I Have Rich Experience and Knowledge in Our Industry.