← Вернуться к курсу: C# from scratch

Classes, objects and properties

Видео скоро появится

Until now you have worked with types that C# already provides: int, string, List<T>. But real programs talk about things from their own world: customers, products, orders, players. Object-oriented programming lets you create your own types that bring data and behavior together. A class is the blueprint, the description of what something is like; an object is each concrete item built from that blueprint. From a Product class you can create a thousand objects: a coffee, a tea, a cake, each with its own data.

Declaring a class

A class is declared with the word class and a PascalCase name. Inside go its members: properties store the data and methods define what the object knows how to do. To create an object you use new. Members are accessed with a dot: product.Name. Important: in a program with top-level statements, classes are written after all the statements, usually at the end of the Program.cs file, or in separate files, one per class, which is the usual practice in large projects. The word public in front of a member makes it visible from outside the class.

csharp
var coffee = new Product();
coffee.Name = "Coffee";
coffee.Price = 2.5m;
coffee.Stock = 40;

var tea = new Product { Name = "Tea", Price = 2m, Stock = 15 };  // object initializer

Console.WriteLine(coffee.Describe());   // Coffee: 2.5 (40 in stock)
Console.WriteLine(tea.Describe());      // Tea: 2 (15 in stock)

coffee.Sell(10);
Console.WriteLine(coffee.Stock);        // 30

class Product
{
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public int Stock { get; set; }

    public string Describe() => $"{Name}: {Price} ({Stock} in stock)";

    public void Sell(int quantity)
    {
        Stock -= quantity;
    }
}

Properties: get, set and init

A property looks like a field but is actually a pair of methods: get to read and set to write. The shortest form, { get; set; }, is called an auto-property: the compiler creates the inner variable for you. You can change the visibility of each part: { get; private set; } allows reading from outside but changing only from inside the class, and { get; init; } allows assigning the value only when creating the object, staying fixed afterwards. A property can also be computed, with no storage of its own: public decimal Total => Price * Stock;. With nullability enabled, a string property cannot be left without a value: give it an initial value, such as = "", or mark it required to force assignment when creating the object.

csharp
var player = new Player { Name = "Ana" };
player.AddPoints(50);
player.AddPoints(25);
Console.WriteLine($"{player.Name} has {player.Points} points, level {player.Level}");
// Ana has 75 points, level 1

// player.Points = 1000;        // ERROR: set is private
// player.Name = "Luis";        // ERROR: init-only after creation

class Player
{
    public required string Name { get; init; }
    public int Points { get; private set; }
    public int Level => Points / 100 + 1;      // computed property

    public void AddPoints(int amount)
    {
        if (amount > 0) Points += amount;
    }
}

Static members

Normal members belong to each object: every Product has its own Name. A static member belongs to the class itself and is used with the class name: Math.PI, Console.WriteLine and int.Parse are examples. It is useful for global counters or for utilities that do not depend on any object. If you overuse it, the program becomes hard to test; use it for stateless tools, such as math functions, and not to store application data.

csharp
Console.WriteLine(Temperature.ToFahrenheit(100));   // 212
Console.WriteLine(Counter.Created);                 // 0
new Counter(); new Counter();
Console.WriteLine(Counter.Created);                 // 2

static class Temperature
{
    public static double ToFahrenheit(double celsius) => celsius * 9 / 5 + 32;
}

class Counter
{
    public static int Created { get; private set; }
    public Counter() => Created++;
}

Проверьте себя

Вопрос 1 из 2

What is an object in relation to a class?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →