public override string ToString() { return String.Format("({0}, {1})", X, Y); }
public override string ToString() => "(\{X}, \{Y})"
Could it go even further? This isn't paper after all, on screen why shouldn't it look like; public override string ToString() => "(X, Y)"
where the X and Y are either slight italics or underlined or colored to indicate they mean X and Y the variable not X and Y the letters. The IDE would let you just toggle the state between 'variable' and 'literal' with the keyboard.We also get better array initializers:
public JObject ToJson() {
var r = new JObject();
r["x"] = X;
r["y"] = Y;
return r;
}
becomes: public JObject ToJson() => return new JObject() { ["x"] = X, ["y"] = Y };
That's cool! Next comes the null-conditional operators: public static Point FromJson(JObject json)
{
if (json != null &&
json["x"] != null &&
json["x"].Type == JTokenType.Integer &&
json["y"] != null &&
json["y"].Type == JTokenType.Integer)
{
return new Point((int)json["x"], (int)json["y"]);
}
return null;
}
Becomes... public static Point FromJson(JObject json)
{
if (json?["x"]?.Type == JTokenType.Integer &&
json?["y"]?.Type == JTokenType.Integer)
{
return new Point((int)json["x"], (int)json["y"]);
}
return null;
}
The check against JTokenType.Integer is just to avoid a casting exception. The null checks are just to avoid null exceptions. I wonder if the compiler could ever handle something like 'this if you can, else null', without actually having any exceptions getting throw and caught underneath: public static Point FromJson(JObject json) =>
return new Point((int)json["x"], (int)json["y"]) ?: null;