C# OOP
C# is object-oriented from the ground up: every method lives inside a class or struct, so there is no writing code outside one. It is a way of organizing code around objects: bundles of data and the behavior that acts on that data. C# is built for OOP, so understanding these ideas is the key to writing larger, well-structured programs.
What is Object-Oriented Programming?
Procedural programming writes code as a list of instructions and functions that operate on data. Object-oriented programming, by contrast, groups related data and behavior together into objects. Each object represents a real or conceptual 'thing' in your program, such as a Car, a User, or a BankAccount, and knows how to work with its own data.
OOP tends to make code easier to reuse, maintain, and reason about. Once you build a well-designed class, you can create many objects from it and use them in many programs without rewriting the logic.
- OOP is faster and easier to work with as programs grow larger.
- OOP gives programs a clear structure built from cooperating objects.
- OOP follows the DRY principle (Don't Repeat Yourself), keeping code shorter and easier to maintain.
- OOP makes it possible to create reusable pieces of code with less effort and less development time.
Classes and Objects
Classes and objects are the two central ideas in OOP. A class is a template or blueprint; an object is a concrete instance created from that blueprint. For example, a class named Car describes what every car has (a brand, a color) and what it can do (drive). Each actual car you create from it is an object.
A simple class and object
class Car
{
public string brand = "Ford";
public string color = "red";
}
class Program
{
static void Main()
{
Car myCar = new Car();
Console.WriteLine(myCar.brand + " - " + myCar.color);
}
}
// Output:
// Ford - redThe Four Pillars of OOP
As you continue, you will meet four core principles that OOP is built on. Encapsulation keeps an object's data safe and controlled. Inheritance lets one class reuse another. Polymorphism lets one action behave differently depending on the object. Abstraction hides complex details behind a simple interface.
One class, many objects
class Dog
{
public string name = "Unknown";
}
class Program
{
static void Main()
{
Dog dog1 = new Dog();
Dog dog2 = new Dog();
dog1.name = "Rex";
dog2.name = "Bella";
Console.WriteLine(dog1.name);
Console.WriteLine(dog2.name);
}
}
// Output:
// Rex
// BellaExercise: C# OOP
What are the four main pillars of object-oriented programming in C#?