This content originally appeared on DEV Community and was authored by hamza zeryouh
This C# 9+ feature can replace multiple if statements
Instead of:
if (shape is Circle c) { /* ... */ }
else if (shape is Rectangle r) { /* ... */ }
else if (shape is Triangle t) { /* ... */ }
Do this:
var area = shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
Triangle t => t.Base * t.Height / 2,
_ => throw new ArgumentException("Unknown shape")
};
Benefits:
More readable
Safer (compiler checks exhaustiveness)
Easier to maintain
What’s your favorite modern C# feature?
This content originally appeared on DEV Community and was authored by hamza zeryouh