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:
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:
Modularity: OOP breaks down a program into smaller, more manageable parts (objects) that can be worked on independently.
Reusability: Objects can be reused in different parts of a program or in different programs altogether, reducing the need to rewrite code.
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.
Inheritance: OOP allows new classes (child classes) to inherit properties and methods from existing classes (parent classes), promoting code reuse and reducing redundancy.
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 /> ✧( • ᴗ - ) ✧