Object-Oriented Programming (OOP)

Beginner Updated February 11, 2025

📦 Object-Oriented Programming (OOP) in C#

C# is an object-oriented language, which means it revolves around classes and objects.

🔹 Defining a Class and Creating an Object

class Car
{
    public string Model;
    public int Year;

    public void Honk()
    {
        Console.WriteLine("Beep!");
    }
}

Car myCar = new Car();
myCar.Model = "Toyota";
myCar.Year = 2022;
myCar.Honk();  // Output: Beep!

🔧 Error Handling in C#

C# uses try-catch blocks for handling exceptions:

try
{
    int x = 5;
    int y = 0;
    int result = x / y;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
}

🗃️ Arrays and Lists

🔸 Array

int[] numbers = {1, 2, 3, 4, 5};
Console.WriteLine(numbers[0]);  // Output: 1

🔸 List

List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Console.WriteLine(names[1]);  // Output: Bob