Classes
Classes are the fundamental building blocks of object-oriented programming (OOP) in C#. They act as blueprints or templates for creating objects, which are instances of classes. Classes encapsulate data (fields) and behavior (methods), providing a structured way to organize and manage related code.
Declaring Classes
Classes are declared using the class keyword followed by the class name and curly braces enclosing the class members:
class Car {
// Fields (data)
private string brand;
private string model;
private int year;
// Methods (behavior)
public void StartEngine() {
Console.WriteLine("Car engine started.");
}
public void Accelerate() {
Console.WriteLine("Car is accelerating.");
}
public void StopEngine() {
Console.WriteLine("Car engine stopped.");
}
}
Objects
Objects are instances of classes, representing specific entities in the real world. They encapsulate the state of the class (fields) and can execute the methods defined in the class.
Creating Objects
Objects are created using the new keyword followed by the class name and parentheses:
Car myCar = new Car(); // Create an object of the Car class
Accessing Class Members
Class members, both fields and methods, are accessed using the dot notation:
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2023;
myCar.StartEngine();
myCar.Accelerate();
myCar.StopEngine();
Example: Bank Account
Consider a bank account class:
class BankAccount {
// Fields
private string accountNumber;
private double balance;
// Methods
public
void
Deposit(double amount) {
balance += amount;
}
public
void
Withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
Console.WriteLine("Insufficient funds.");
}
}
public double GetBalance() {
return balance;
}
}
Creating an account object and performing operations:
BankAccount myAccount = new BankAccount();
myAccount.accountNumber = "12345678";
myAccount.balance = 500.00;
myAccount.Deposit(200.00);
Console.WriteLine("Balance after deposit: " + myAccount.GetBalance());
myAccount.Withdraw(300.00);
Console.WriteLine("Balance after withdrawal: " + myAccount.GetBalance());
Conclusion
Classes and objects are essential concepts in C# OOP, enabling the creation of structured, maintainable, and reusable code. Classes provide blueprints for objects, while objects encapsulate data and behavior, allowing programmers to model real-world entities and their interactions. Understanding classes and objects is crucial for developing effective C# applications.