Tagged: Matching

Pattern Matching in C# 7.0 Switch Statements

I was trying to figure out what would be the best way to list out partial views based on Model type and found C# 7.0 new feature ‘Pattern matching in switch statements’ would be great fit for the scenario.

Before only string/integer can be compared, now you can compare on any type of object. Below is the example shows switch case based on Model Interface type.

@model Synthesis.IStandardTemplateItem

@switch (Model)
{
case INavigationColumnItem nci:
//Take any action
break;
case IColumnNavigationFolderItem ncfi:
//Take any action
break;
case IHeaderLogoItem hli:
//Take any action
break;
case IHeaderNavigationLinkItem hnli:
//Take any action
break;
case IHeaderPhoneNumberItem hpni:
//Take any action
break;
}

Checkout more cool new C# 7.0 features here. Happy coding.

1