C# 8.0 is coming soon and we have already seen some amazing features lined up for C# 8.
Have a look here for some features of C# 8.
Pattern matching
Pattern matching has already been introduced with C# 7.1 and I have written an article on the same which you can find here.
.Net team has extended some more features along with Pattern matching.
One of the extended features is for Switch expression.
Till now we are used to write Switch statements as below:
public static string RepairCar(int caseSwitch) { switch (caseSwitch) { case 1: return "Case 1"; break; case 2: return "Case 2"; break; default: return "Default case"; break; } }
With new proposal in C# 8.0, repetitive code can be removed and along with that return can also be removed from individual Switch cases.
Proposed approach would give a cleaner, more readable and more maintainable solution for the Switch statements.
So with C# 8, Switch statement would look like below:
static string RepairCar(Car brokenCar) { return brokenCar switch { Ferari p => $"Ferari details: {p.Model}", BMW s => $"BMW details: {s.Model} {s.Age} ({s.CurrentSpeed})", _ => $"{brokenCar.Model} {brokenCar.Age}" //// Default }; }
Note: Exact syntax would be announced soon so => may change to : in the future but rest would remain same as above.
Some more examples
Apart from this, one example I got from the .Net GitHub page as below, though we can see case in below code but they are planning to remove it from the syntax.
var areas = from primitive in primitives let area = primitive switch ( case Line l: 0, case Rectangle r: r.Width * r.Height, case Circle c: Math.PI * c.Radius * c.Radius, case _: throw new ApplicationException() ) select new { Primitive = primitive, Area = area };
Ref of code: https://github.com/dotnet/csharplang/blob/master/proposals/patterns.md#a-match-expression-contributed-by-orthoxerox
Hope it helps.
Love it to hear! Liitle more formatting more like in if cases and will be rocket solid:
static string RepairCar(Car brokenCar)
{
return brokenCar switch
{
p is Ferari => $”Ferari details: {p.Model}”,
s is BMW => $”BMW details: {s.Model} {s.Age} ({s.CurrentSpeed})”,
_ => $”{brokenCar.Model} {brokenCar.Age}” //// Default
};
}
LikeLike
Yes right. You can always post a new thread and suggest the changes to the .Net team.
LikeLike
It would certainly look cleaner, more readable and more maintainable if you could add some indentation 🙂
LikeLiked by 1 person
Hey, please check here for more examples: https://github.com/dotnet/csharplang/issues/1395
LikeLike
You don’t need `break` if you `return` right away from `case`
LikeLike
Hello blogger, i’ve been reading your content for some time and I really
like coming back here. I can see that you probably don’t make money on your site.
I know one interesting method of earning money,
I think you will like it. Search google for: dracko’s tricks
LikeLike
Okay thanks.
LikeLike
Hey, thanks for the information.
LikeLike