← C# from Scratch Lesson 26 of 39 · 5 XP

OOP

Theory

Machine translation, not yet reviewed by a native speaker.

Object-oriented programming is a way of building a program out of objects: each one has data (fields) and behaviour (methods).

  • A class is a blueprint: "an enemy has health and can attack";
  • an object is a specific instance made from the blueprint: an orc with 50 HP, a goblin with 20 HP.

The four ideas of OOP:

  1. Encapsulation — the data is hidden inside the object and can be changed only through its methods and properties. You can't do hp = -1000 and bypass the rules.
  2. Inheritance — a new class takes everything from an existing one and adds its own: Boss : Enemy.
  3. Polymorphism — one call, different behaviour: enemy.Attack() works in its own way for an orc and for a mage.
  4. Abstraction — show "what it can do", hide "how it's done": an IDamageable interface with a TakeDamage method.

In C# everything is an object of a class, even int (it's the System.Int32 struct with methods: 5.ToString()). A C# program without classes is impossible — the top-level statements we've been writing are also tucked away by the compiler into a Program class.

Under the hood. An object of a class lives on the heap; a variable holds only a reference to it. Unneeded objects are cleaned up by the garbage collector (GC) — you don't write free as in C. A struct (like int, double) is stored right in the variable and is copied on assignment.

Next up — each of these ideas in practice.

Sign up for free to mark finished lessons and track your progress.