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?

Property in C#

Last updated at Posted at 2025-07-21

はじめに

C#のプロパティの基本的な文法を記載しています。解説や応用的な使用方法は他記事を参照ください。

プロパティ 読取/書込 (get/set)

class Person
{
    //プロパティ未使用    
    // 呼び出し側のコード
    //    Person man = new Person();
    //    man.SetAge1(1);
    //    int age1 = man.GetAge1();
    private int age1;
    public int GetAge1()
    {
        return age1;
    }
    public void SetAge1(int value)
    {
        age1 = value;
    }

    //基本的なプロパティ
    //  呼び出し側のコード
    //    Person man = new Person();
    //    man.Age2 = 2;
    //    int age2 = man.Age2;
    private int age2;
    public int Age2
    {
        get { return age2; }
        set { age2 = value; }
    }

    //ラムダ式を使用したプロパティ
    //  呼び出し側のコード
    //    Person man = new Person();
    //    man.Age3 = 3;
    //    int age3 = man.Age3;
    private int age3;
    public int Age3
    {
        get => age3;
        set => age3 = value;
    }

    //自動実装プロパティ
    //  呼び出し側のコード
    //    Person man = new Person();
    //    man.Age4 = 4;
    //    int age4 = man.Age4;
    public int Age4 { get; set; }
}

プロパティ 読取専用 (get only)

class Person
{
    //読取専用の値(コンストラクタ等で値を設定)
    private int age11 = 11;
    private int age12 = 12;
    private int age13 = 13;
    private int age14 = 14;
    
    //プロパティ未使用
    // 呼び出し側のコード
    //    Person man = new Person();
    //    int age11 = man.GetAge11();
    public int GetAge11()
    {
        return age11;
    }

    //基本的なプロパティ
    //  呼び出し側のコード
    //    Person man = new Person();
    //    int age12 = man.Age12;
    public int Age12
    {
        get { return age12; }
    }

    //ラムダ式を使用したプロパティ1
    //  呼び出し側のコード
    //    Person man = new Person();
    //    int age13 = man.Age13;
    public int Age13
    {
        get => age13;
    }

    //ラムダ式を使用したプロパティ2
    //  呼び出し側のコード
    //    Person man = new Person();
    //    int age14 = man.Age14;
    public int Age14 => age14;

    //自動実装プロパティ
    //  呼び出し側のコード
    //    Person man = new Person(15);
    //    int age15 = man.Age15;    
    //コンストラクタで一度だけプロパティに値を設定
    public Person(int value)
	{
		Age15 = value;
	}
    //プロパティ
    public int Age15 { get; }
}
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?