Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created February 5, 2015 13:58
Show Gist options
  • Select an option

  • Save ufcpp/8719758b3a15c7e398c2 to your computer and use it in GitHub Desktop.

Select an option

Save ufcpp/8719758b3a15c7e398c2 to your computer and use it in GitHub Desktop.
// C# 5 以前で、きっちり作るなら
// プロパティ1つごとに5か所ずつ同じものを書かないと行けない
// しかも、プロパティ/フィールド、コンストラクターで結構場所が離れる
public class Point
{
public int X { get { return _x; } }
private readonly int _x;
public int Y { get { return _y; } }
private readonly int _y;
public Point(int x, int y)
{
_x = x;
_y = y;
}
}
// C# 5 以前で、多少さぼる
// private set な自動実装プロパティを使用
// 自動実装で作られるフィールドは readonly ではなく、private なだけでクラス内からは書き換え可能
public class Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
}
// C# 5 以前で、さぼる
// new Point(1, 2) って書くのをあきらめて、new Point { X = 1, Y = 2 } と書く
// set も public になってしまっていて大変残念
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
// C# 7 の秘めた可能性
// これだけで readonly なフィールドを持った、get-only なプロパティが生成される
public class Point(int X = 0, int Y = 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment