Object-Oriented Programming in C#

Understanding objects, classes, and OOP basics

Posted by Rodrigo Castro on November 9, 2024

C# is an object-oriented language. That means you build programs using classes and objects.

🏗️ What is a Class?

A class is a blueprint for objects.

1
2
3
4
5
6
7
8
class Car
{
    public string Model;
    public void Honk()
    {
        Console.WriteLine("Beep!");
    }
}

🚗 What is an Object?

An object is a specific thing built from a class.

1
2
3
Car myCar = new Car();
myCar.Model = "Toyota";
myCar.Honk(); // Beep!

🌟 OOP Concepts

  • Encapsulation: Keeping data and code together in one place.
  • Inheritance: One class (child) can use code from another (parent).
  • Polymorphism: One interface, many implementations.

📝 Why use OOP?

  • Organizes code around real things.
  • Makes code more reusable and easier to maintain.

💡 Try It!

Create a Student class with a property Name and a method Introduce() that prints “Hi, I’m {Name}!”.

1
2
3
4
5
6
7
8
class Student
{
    public string Name;
    public void Introduce()
    {
        Console.WriteLine($"Hi, I'm {Name}!");
    }
}

Next: Classes, objects, and methods in more detail!