by rkagerer · 6y ago · 0 comments
public static double ComputeArea(object shape) {
switch (shape) {
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
case Rectangle r:
return r.Height * r.Length;
default:
throw new ArgumentException(
message: "shape is not recognized",
paramName: nameof(shape));
}
}
The when clause can be used to deal with special cases (e.g. to avoid division by 0 when a dimension is 0). public static double ComputeArea(object shape) =>
shape switch
{
Square s => s.Side * s.Side,
Circle c => c.Radius * c.Radius * Math.PI,
Rectangle r => r.Height * r.Length
_ => throw new ArgumentException(
message: "shape is not recognized",
paramName: nameof(shape))
};In 2020 Pattern Matching is just a elementary feature everyone wants to have in all general purpose language. Like async/await. Or LINQ. That is just 101 for languages from now on.
public static double ComputeArea(object shape) =>
shape switch {
Square s => s.Side * s.Side,
Circle c => c.Radius * c.Radius * Math.PI,
Rectangle r => r.Height * r.Length,
_ => throw new ArgumentException( message: "shape is not recognized", paramName: nameof(shape));
}[0] Roslyn Analyzers: https://docs.microsoft.com/en-us/visualstudio/code-quality/r...
In fact, `where` isn't a reserved keyword, either--you can have an identifier named `where`.[1]
To an existing C# programmer, `where` makes a lot of sense, since it's used for matching elsewhere (e.g., LINQ).
[0]: https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
[1]: https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
What i vaguely remember from my OCaml times, I think working with lists is the major gap they have. And that is non-trivial.