Skip to main content

Object-Oriented Programming (OOP) in C#

Object-Oriented Programming (OOP) is a paradigm that organizes software into objects, which combine data (attributes) and behaviors (methods).
In C#, OOP is one of the fundamental pillars for building modular, reusable, and maintainable applications.


Introduction to UML

UML (Unified Modeling Language) is a standardized modeling language that helps to visualize, specify, and document object-oriented systems before implementing them.

Basic UML principles

  • Class diagrams: Represent the system's structure by showing classes, attributes, methods, and relationships.
  • Use case diagrams: Describe how users (actors) interact with the system.
  • Sequence diagrams: Show the interaction between objects over time.

Simple class diagram example

+-------------------+
| Person |
+-------------------+
| - name: string |
| - age: int |
+-------------------+
| + Greet(): void |
+-------------------+
info
  • Draw.io (Diagrams.net) → Free and online.
  • StarUML → Powerful and cross-platform.
  • Visual Paradigm → Focused on large projects.
  • PlantUML → Text-based, ideal for programmers.

Recommended resource: UML in 24 hours - Martin Fowler.


OOP Fundamentals in C#

info

In C#, everything begins with classes and objects.

To work with objects in C#, it's necessary to first define a class. A class is a blueprint that describes the data and behavior of the objects that will be created from it. An object is an instance of a class—a concrete realization of the structure defined by the class.

Classes and objects

A class in C# is defined using the class keyword, followed by the class name and a body containing its members (properties, methods, etc.)

  • Class: A model defining attributes and behaviors.
  • Object: A concrete instance of a class.
public class Person
{
// Attributes
public string Name { get; set; }
public int Age { get; set; }

// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}

// Method
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}

// Usage
Person p1 = new Person("Ana", 25);
p1.Greet();

Constructors in C#

Constructors in C# are special methods invoked automatically when an instance of a class is created. They are used to initialize the state of the object and establish default values for its fields. Constructors can be overloaded to provide different ways of initializing objects.

Basic Constructor

A constructor uses the same name as the class and does not have a return type. Its primary purpose is to initialize the object's fields or properties when instantiated.

public class Person
{
public string Name { get; set; }
public int Age { get; set; }

// Constructor
public Person()
{
Name = "mario";
Age = 21;
}
}

In this example, the Person class has a constructor that initializes Name as "mario" and Age as 21. This constructor is called when a new instance of Person is created without arguments.

Person person = new Person();
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Name: mario, Age: 21

::: warning

All objects are created with the same default data, so it is not recommended to leave them like this. :::

Parameterized Constructor

Constructors can also take parameters to initialize the object with specific values.

public class Person
{
public string Name { get; set; }
public int Age { get; set; }

// Parameterized Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

In this example, the Person class has a parameterized constructor allowing you to set Name and Age upon creating an instance of Person.

Person person = new Person("John", 30);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Name: John, Age: 30

Overloaded Constructors

You can have multiple constructors in a class, each with different parameters. This is known as constructor overloading.

public class Person
{
public string Name { get; set; }
public int Age { get; set; }

// Left empty to access properties and methods without initializing values
public Person(){}

// Parameterized constructor
public Person(string name)
{
Name = name;
Age = 0;
}

// Parameterized constructor with age
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

In this example, the Person class has three constructors:

  1. Left empty to access properties and methods without setting defaults.
  2. The second initializes Name with a specified value and Age to 0.
  3. The third initializes Name and Age with specified values.
Person instance = new Person();
Person person2 = new Person("Maria");
Person person3 = new Person("Carlos", 40);

Console.WriteLine($"Person2 - Name: {person2.Name}, Age: {person2.Age}"); // Name: Maria, Age: 0
Console.WriteLine($"Person3 - Name: {person3.Name}, Age: {person3.Age}"); // Name: Carlos, Age: 40

Advanced OOP Principles

OOP in C# relies on four fundamental pillars:

1. Abstraction

Modeling real entities by showing only the relevant details.

abstract class Shape
{
public abstract double CalculateArea();
}

2. Encapsulation

Controlling access to internal data through properties and access modifiers.

public class BankAccount
{
private decimal balance;

public void Deposit(decimal amount) => balance += amount;
public decimal CheckBalance() => balance;
}

3. Inheritance

Allows a class to inherit attributes and methods from another.

public class Animal
{
public void Eat() => Console.WriteLine("The animal is eating");
}

public class Dog : Animal
{
public void Bark() => Console.WriteLine("Woof!");
}

4. Polymorphism

The same method can behave differently depending on the context.

public class Shape
{
public virtual void Draw() => Console.WriteLine("Draw shape");
}

public class Circle : Shape
{
public override void Draw() => Console.WriteLine("Draw circle");
}

Abstract classes, interfaces, and access modifiers

  • Abstract classes
    Cannot be directly instantiated. They serve as templates for other classes.

    public abstract class Vehicle
    {
    public abstract void Move();
    }
  • Interfaces
    Define a contract that classes must implement.

    public interface IVehicle
    {
    void Move();
    }

    public class Car : IVehicle
    {
    public void Move() => Console.WriteLine("The car is moving");
    }
  • Access modifiers
    Control the visibility of classes and members:

    • public → Accessible from anywhere.
    • private → Only within the class.
    • protected → Accessible in the class and its derivatives.
    • internal → Accessible within the same project.

info
  • UML allows to visualize and plan object-oriented systems.
  • OOP in C# is built upon classes and objects that define data and behaviors.
  • The OOP pillars are: abstraction, encapsulation, inheritance, and polymorphism.
  • C# supports abstract classes, interfaces, and access modifiers to structure code securely and reusably.