しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

C#のプロパティーの書き方

基本的なところですがC#のプロパティーの書き方について調べました。

プロパティーは下のように2種類の書き方があります。

class MyClass
{
    public int myProperty1 = 0;
    public int myProperty2 {
        get { return 0; }
        set { int myValue = value; }
    }
}

それぞれ下のように呼び出します。

MyClass c = new MyClass();
Debug.Log(c.myProperty1); // → 0
Debug.Log(c.myProperty2); // → 0
c.myProperty1 = 2;
Debug.Log(c.myProperty1); // → 2

プロパティーはセッターだけprivateにするといった事も可能です。

class MyClass
{
    public int myProperty1 = 0;
    public int myProperty2 {
        get { return 0; }
        private set { int myValue = value; }
    }
}