OOP: Klassen und Objekte in C# (.NET): Eine ausführliche Anleitung
What is it and why? (a real-life analogy)
Imagine you decided to build a city from LEGO bricks. You have a box of parts, but to build, for example, a house, you need a blueprint. Using one blueprint, you can assemble hundreds of identical houses. And if you want to add a window or a door to the house, you just change the blueprint, and all new houses will already have windows.
In programming, a class is exactly such a blueprint. It describes what an object consists of (what properties it will have) and what it can do (what methods). An object is a specific house built according to this blueprint. Each object has its own property values: one house has a red roof, another has a blue one, but both are houses.
Important: A class is a data type that you create yourself. An object is an instance of this type, living in the computer's memory.
Why is this needed? Imagine you are writing a game. You have 100 enemies. If you don't use classes, you would have to manually specify coordinates, health, speed, and actions for each enemy. But with classes, you describe the Enemy class once, and then create 100 objects of this class — fast, convenient, and if you need to add a new property to all enemies, you only change the class.
Theory: how it works internally
When a program starts, the computer allocates memory for data. A class is just a description; it doesn't take up memory space until you create an object. When you write new ClassName(), the following happens:
- The computer allocates space in memory (in the heap) for the new object.
- A special method is called — the constructor, which initializes the object's properties with initial values.
- A reference to this object is stored in the variable you work with.
Each object stores its own property values. But the methods for all objects of the same class are shared. The computer does not copy methods for each object; that would be too wasteful. Methods are stored in one place, and when called, they are passed a reference to the specific object they need to work with.
Important: A variable that stores an object actually stores not the object itself, but a reference to it. If you assign one variable to another, they will refer to the same object. Changes made through one variable will be visible through the other.
In C#, there are two main types of data: value types (int, double, bool, struct) and reference types (class, string, array). Classes belong to reference types. This means that when you pass an object to a method, you pass a reference, not a copy. The method can modify your original object.
Syntax in C# (.NET): all forms and variants
Let's break down how to declare classes and create objects in C#. We'll start with the simplest and gradually increase complexity.
Class Declaration
// Simplest form of class declaration
class Car
{
// Fields (data fields) — variables that store the object's state
public string brand;
public string model;
public int year;
// Method — an action the object can perform
public void Honk()
{
Console.WriteLine("Beep beep!");
}
}
Creating an Object (Class Instance)
// Creating an object of the Car class
Car myCar = new Car();
// Now you can access its fields and methods
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2020;
myCar.Honk(); // Outputs: Beep beep!
Constructors
A constructor is a special method that is called when an object is created. It is needed to immediately set the initial values of properties.
class Car
{
public string Brand { get; set; } // Property — a modern approach
public string Model { get; set; }
public int Year { get; set; }
// Parameterless constructor (default)
public Car()
{
Brand = "Unknown";
Model = "Unknown";
Year = 2000;
}
// Parameterized constructor
public Car(string brand, string model, int year)
{
Brand = brand;
Model = model;
Year = year;
}
}
// Usage
Car car1 = new Car(); // Without parameters
Car car2 = new Car("BMW", "X5", 2022); // With parameters
Properties
In C#, it is common to use properties instead of fields. They look like fields but can contain logic inside.
class Person
{
// Auto-implemented property — the compiler creates the storage field itself
public string Name { get; set; }
// Property with validation
private int age;
public int Age
{
get { return age; }
set
{
if (value >= 0 && value <= 150)
age = value;
else
Console.WriteLine("Invalid age!");
}
}
// Read-only property
public string Greeting { get; } = "Hello!";
}
// Usage
Person p = new Person();
p.Name = "Anna";
p.Age = 25; // All good
p.Age = 200; // Outputs: Invalid age!
Access Modifiers
| Modifier | Description |
|---|---|
public |
Accessible from anywhere |
private |
Accessible only within this class |
protected |
Accessible within the class and in derived classes |
internal |
Accessible within the same assembly (project) |