C# 6.0での自動プロパティの前に、従来の自動プロパティについて確認しておきましょう。
これまでプロパティ定義は以下のように記述する必要がありました。
PatternAクラスでは、プロパティWidthの初期化は、フィールド_widthの宣言と同時に実行しています。
PatternBクラスでは、コンストラクタ内で初期化を行っています。
public class PatternA
{
private int _width = 20; // 初期化
public int Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
}
public class PatternB
{
// コンストラクタ
public PatternB()
{
this.Width = 20; // 初期化
}
public int Width { get; set; }
}
C# 6.0の場合は、以下のように簡潔に記述することができるようになりました。
プロパティの定義と初期化が同時に行えるので、以前と比較してコード量が減っています。
public class CS6
{
public int Width { get; set; } = 20;
}
getのみの定義と初期化も可能です。この場合は以下のように記述します。
public class CS6
{
public int Width { get; } = 20;
}
Please follow and like us:
コメント