Wednesday, 26 July 2017

Its the little things...

In the history of C# we have been spoiled by every version having excellent new language features in. We had Generics, Linq, Tasks, async/await which were massive hitters and transformed the way we worked and wrote code.

C#7 however I found has given us lots of little improvements that make things smoother and easier which has been great. One feature I hadn't really used yet though was the new Pattern Matching, this wasn't because I hadn't wanted to but more I hadn't seen a time to really use it.

That was until tonight.

A year or so ago I had a scenario where I had to take a base type and then1 return the appropiate mobile view to render. Prior to Pattern Matching I ended up with something like:
if (value is HoldingPage)
return new LoadingView();
}
var listingPage = value as ListingPage;
if (listingPage != null)
{
return new ListingView(listingPage);
}
Tonight I needed to add a new view into this code and decided it needed tidying up. Pattern Matching allows us to test that a value has a certain shape, and when its matched provide a variable name for it which we can then continue to use. So rather than have lots of as statements with null checks  we can simply do:
switch (value)
{
case HoldingPage p:
return new LoadingView();
case ListingPage p:
return new ListingView(p);
case ContentPage p:
var sectionId = parameter as string;
return new DetailsView(p, sectionId);
case IndexPageWithTabledSections p:
return new TabledSectionListingView(p.Sections);
}

Less code and far more concise and readable. What a great feature!

2 comments:

  1. Extra pro-tip: if you're not using the value, as in the case of HoldingPage here, then you can use an underscore instead of a variable name to explicitly discard the value without assigning a variable. I.e.:

    case HoldingPage _:
    return new LoadingView();

    ReplyDelete