0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】プロパティとは?

Posted at

プロパティとは?

プロパティは、クラスの内部データ(フィールド)に安全にアクセスするための仕組みです。
つまり、「値の読み書きをコントロールする窓口」みたいなもの。

たとえば、こんなクラスがあったとします。

class Person
{
    private string name; // フィールド

    public string Name
    {
        get { return name; }     // 値を読み取る
        set { name = value; }    // 値を書き込む
    }
}

この Name が「プロパティ」です。
外部のコードからは、まるで変数のように使えます。

var p = new Person();
p.Name = "太郎";     // setが呼ばれる
Console.WriteLine(p.Name); // getが呼ばれる

自動実装プロパティ

C#では、プロパティはもっと簡単に書けます。

public class Person
{
    public string Name { get; set; }
}

このように書くと、裏でC#が自動的にフィールドを作ってくれます。
いわゆる「自動実装プロパティ」です。
簡単なクラスなら、これで十分です。

getだけ・setだけもOK

読み取り専用や書き込み専用のプロパティも作れます。

public class Person
{
    public string Name { get; } = "太郎"; // 読み取り専用
}

あるいは、値を設定する処理だけ特別にしたい場合

public int Age
{
    get { return age; }
    set
    {
        if (value >= 0)
            age = value;
    }
}

まとめ

  • プロパティはフィールドを安全に扱うための仕組み
  • get / set でアクセスをコントロールできる
  • 自動実装プロパティでシンプルに書ける
  • 「カプセル化」を実現する大事な要素!

C#の世界では、public フィールドはほぼ使いません
外部公開したい値は、必ずプロパティにするのが基本です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?