by aar0nsa3nz · 6y ago · 0 comments
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...