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 Player
{
    public int hp; // フィールド
}

これは単純に「変数をクラスの中に置いただけ」。
外部からもこうしてアクセスできます

Player p = new Player();
p.hp = 100;
Console.WriteLine(p.hp); // 100

シンプルですが、値を自由に変更できてしまうのが弱点です。
つまり、安全性が低い

プロパティとは

プロパティは、フィールドへのアクセスを制御するための仕組みです。
値を取得(get)・設定(set)するときに処理を挟むことができるのがポイント!

class Player
{
    private int hp; // フィールド(隠す)
    
    public int HP // プロパティ
    {
        get { return hp; }
        set
        {
            if (value < 0)
                hp = 0; // 不正な値を防ぐ
            else
                hp = value;
        }
    }
}

外部から見ると使い方は同じ

Player p = new Player();
p.HP = -50; // 不正値 → 自動的に0に補正
Console.WriteLine(p.HP); // 0

でも内部では、ちゃんとチェックが入っています。
これがカプセル化の力です。

違いまとめ

項目 フィールド プロパティ
定義 クラス内の変数 フィールドへのアクセスを管理する仕組み
アクセス制御 不可 get / set で制御できる
カプセル化 できない できる
コードの安全性 低い 高い
外部からの見え方 変数 変数っぽく見えるメソッド

どっちを使うべき

外部からアクセスさせたいなら「プロパティ」、
クラス内だけで使うなら「フィールド」

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?