C# Fundamentals of OOP

C# Fundamentals of OOP

Object Oriented Programming

Object-oriented programming (OOP) in C# involves creating classes as blueprints (or templates) to generate new objects (instances), encapsulating data and behavior within them.

What a hell?! Ok let's use simpler words:
Imagine we are developing software, and we need to create 2 (or more) new entities John and Ana. They are different from each other, the names are different, ages, etc... But they have similarities too, both have a name and an age. To avoid code repetition, would be helpful to create a template called "Person" that has methods for names and ages. Then, we can use this template to create John and Ana, giving them their own unique names and ages, while still using the shared methods from the "Person" template.

In the code example below we are creating the class (blueprint) Person, which has methods Name, Age, and Introduce.

From this class, we will generate 2 objects, "John" and "Ana".

John and Ana are 2 new entities with the same methods, Name, Age, and Introduce.

using System;

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

    public void Introduce() {
        Console.WriteLine($"Hi, my name is {Name} and I am {Age} years old.");
    }
}
// At Main Program:
class Program {
    static void Main(string[] args) {
        // Creating objects (instances) of the Person class
        Person John= new Person();
        John.Name = "John Smith";
        John.Age = 30;

        Person person2 = new Person();
        Ana.Name = "Ana Doe";
        Ana.Age = 25;

        // Calling the Introduce method for each person
        person1.Introduce();
        person2.Introduce();
    }
}

Benefits of OOP:

  1. Modularity: OOP breaks down a program into smaller, more manageable parts (objects) that can be worked on independently.

  2. Reusability: Objects can be reused in different parts of a program or in different programs altogether, reducing the need to rewrite code.

  3. Encapsulation: Objects hide their internal workings and only expose necessary functionalities, making it easier to understand and use them without worrying about their implementation details.

  4. Inheritance: OOP allows new classes (child classes) to inherit properties and methods from existing classes (parent classes), promoting code reuse and reducing redundancy.

  5. Polymorphism: Objects of different classes can be treated as objects of a common superclass, allowing for flexibility and extensibility in the code.

Overall, OOP promotes code organization, reusability, and maintainability, making it a powerful paradigm for building software systems of varying sizes and complexities.

If you liked this post...

<Tag along /> ✧( • ᴗ - ) ✧

Did you find this article valuable?

Support Marcia Satie by becoming a sponsor. Any amount is appreciated!