Part 6: Object-Oriented Programming (OOP) in C#

Image description

Object-Oriented Programming (OOP) is a paradigm that organises code around objects and classes, making it easier to develop modular and reusable applications. C# is designed to fully leverage this paradigm. In this guide, we will explore the basics of OOP, constructors, and properties in C#.

1. Basic Concepts of OOP

1.1 Classes and Objects

A class is a blueprint that defines the properties and behaviours of an object. Objects are instances of classes.

Example of a Class and Object

public class Conferences
{
    public string Name;
    public int PeopleNumber;

    public void Welcome()
    {
        Console.WriteLine($"Hello, this is {Name} and we have {PeopleNumber} people.");
    }
}

// Creating an object
Conferences conferences = new Conferences();
conferences.Name = "Codú";
conferences.PeopleNumber = 30;
person.Welcome();

In this example, Conferences is the class, and conferences is the object created from that class.


1.2 Encapsulation

Encapsulation protects a class's data by restricting direct access to its properties and exposing controlled methods to modify or access them. This is achieved using access modifiers like private and public.

Example of Encapsulation

public class BankAccount
{
    private decimal balance;

    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            balance += amount;
            Console.WriteLine($"Deposit successful. Current balance: {balance}");
        }
        else
        {
            Console.WriteLine("The amount must be greater than zero.");
        }
    }

    public void DisplayBalance()
    {
        Console.WriteLine($"Current balance: {balance}");
    }
}

// Creating an object and using methods
BankAccount account = new BankAccount();
account.Deposit(2000);
account.DisplayBalance();

In this example, the balance is protected and can only be modified through the Deposit method.

2. Constructors and Properties

2.1 Constructors

A constructor is a special method that is automatically called when an object is created. It is used to initialise properties.

Example of a Constructor

public class Car
{
    public string Brand;
    public string Model;

    // Constructor
    public Car(string brand, string model)
    {
        Brand = brand;
        Model = model;
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Car: {Brand} {Model}");
    }
}

// Creating an object using the constructor
Car myCar = new Car("Audi", "a7");
myCar.DisplayInfo();

2.2 Properties

Properties provide a way to safely access and modify private fields. They are defined using get and set.

Example of Properties

public class Product
{
    private decimal price;

    public decimal Price
    {
        get { return price; }
        set
        {
            if (value >= 0)
            {
                price = value;
            }
            else
            {
                Console.WriteLine("Price cannot be negative.");
            }
        }
    }
}

// Creating an object and using properties
Product product = new Product();
product.Price = 150;
Console.WriteLine($"Product price: {product.Price}");

3. Practical Example: Creating Classes and Objects

Let’s create a Rectangle class that calculates the area and perimeter of a rectangle.

public class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }

    public Rectangle(double length, double width)
    {
        Length = length;
        Width = width;
    }

    public double CalculateArea()
    {
        return Length * Width;
    }

    public double CalculatePerimeter()
    {
        return 2 * (Length + Width);
    }
}

// Creating an object and using its methods
Rectangle rect = new Rectangle(5.0, 3.5);
Console.WriteLine($"Area: {rect.CalculateArea()}");
Console.WriteLine($"Perimeter: {rect.CalculatePerimeter()}");

4. Advancing in OOP: Inheritance and Polymorphism

4.1 Inheritance

Inheritance allows a class (subclass) to inherit properties and methods from another class (superclass).

Example of Inheritance

public class Animal
{
    public string Name { get; set; }

    public void Eat()
    {
        Console.WriteLine($"{Name} is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine($"{Name} is barking.");
    }
}

// Using inheritance
Dog myDog = new Dog();
myDog.Name = "Toby";
myDog.Eat();
myDog.Bark();

4.2 Polymorphism

Polymorphism allows methods to have different behaviours depending on the context in which they are used.

Example of Polymorphism

public class Bird
{
    public virtual void Fly()
    {
        Console.WriteLine("The bird is flying.");
    }
}

public class Eagle : Bird
{
    public override void Fly()
    {
        Console.WriteLine("The eagle flies at great heights.");
    }
}

// Using polymorphism
Bird myBird = new Eagle();
myBird.Fly();

Object-Oriented Programming in C# enables you to write organised, reusable, and maintainable code. Mastering concepts such as classes, objects, encapsulation, constructors, properties, inheritance, and polymorphism is essential for developing robust and scalable applications.

TipsBeginnersCsharpDotnet
Avatar for Adrián Bailador

Written by Adrián Bailador

🚀 Full-Stack Dev 👨🏻‍💻 .NET Engineer 👾 Geek & Friki 💡 Talks about #dotnet, #csharp, #azure, #visualstudio and a little bit of #nextjs.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.