Pattern Matching in C# Switch

Seamless Integration

Pattern Matching in C# Switch

Switch…Case block is used to provide handling of flow of the program logic based on certain outcome of a variable. Most of the time, we evaluate the variable and depending on exact match, we pass the flow to a case handler like this:

switch (color)
{
case “Red”: gotoRedHandler();
break;
case “Green”: gotoGreenHandler();
break;
default: gotoRainbowHandler();
break;
}

However, when we want to match a partial existence of a text (string comparison – String.contains()), we can do it like below:

switch (overviewType){
   case var positionType when (overviewType.Contains("position type")):
                    jobDetail.PositionType = overviewValue;
                    break;

   case var experience when (overviewType.Contains("experience")):
                    jobDetail.ExperienceRequired = overviewValue;
                    break;

   case var opening when (overviewType.Contains("opening")):
                    jobDetail.AvailablePositions = overviewValue;
                    break;
}

No Comments

Add your comment

two + 10 =