← 講座に戻る: C# from scratch

Constructors, encapsulation and access modifiers

動画は近日公開

A newly created object should always be in a valid state. An account without an owner, a product with a negative price or an order without a customer are errors waiting to happen. Two object-oriented tools help you avoid them: constructors, which force you to provide the necessary data when creating the object, and encapsulation, which hides internal data so that it can only be changed through rules controlled by the class itself.

Constructors

A constructor is a special method with the same name as the class and no return type. It runs when you write new and is used to give initial values. You can have several, with different parameters, and one can reuse another with : this(...). The word this refers to the current object and is used to distinguish a parameter from a property with the same name. Since C# 12 there are primary constructors, which declare the parameters on the class line itself: class Point(int x, int y). They are convenient for simple classes, although classic constructors are still the clearest when there are validations.

csharp
var a = new Person("Ana", 29);
var b = new Person("Luis");          // uses the second constructor
Console.WriteLine($"{a.Name} {a.Age}");   // Ana 29
Console.WriteLine($"{b.Name} {b.Age}");   // Luis 18

var p = new Point(3, 4);
Console.WriteLine(p.DistanceToOrigin());  // 5

class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public Person(string name) : this(name, 18) { }   // reuses the first one
}

class Point(double x, double y)           // primary constructor
{
    public double DistanceToOrigin() => Math.Sqrt(x * x + y * y);
}

Encapsulation and access modifiers

Access modifiers decide who can see each member: public (everyone), private (only the class itself, and it is the default for members) and protected (the class and its derived classes, which you will see in week 7); also internal, for the whole project. The golden rule of encapsulation is: data is private and the class exposes only what is necessary through properties and methods. This way, the class can validate each change. A private field is written by convention with an underscore and lowercase, like _balance, and the word readonly prevents assigning it outside the constructor.

csharp
var item = new Product("Notebook", 1200m);
item.ApplyDiscount(10);
Console.WriteLine(item.Price);            // 1080

try
{
    var broken = new Product("Pen", -5m);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);        // Price must be positive
}

class Product
{
    private decimal _price;                // private field
    public string Name { get; }

    public decimal Price
    {
        get => _price;
        private set
        {
            if (value <= 0) throw new ArgumentException("Price must be positive");
            _price = value;
        }
    }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;                     // goes through the validation
    }

    public void ApplyDiscount(int percent)
    {
        Price -= Price * percent / 100;
    }
}

理解度チェック

問題 1 / 2

What is the default access of a class member?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →