In C# 8.0, tuple pattern matching is used to determine whether or not the contents and order of a tuple are as required.
Pattern matching is implemented by comparing tuples and user-defined templates of tuples with the help of switch
expressions.
Although pattern matching was made available in C# 7.0, tuple pattern matching is only available in C# 8.0 and above.
The following program declares a function named sports_i_like
, which takes in one tuple as its parameter. It compares this tuple with tuple templates defined as switch expression cases, and it returns the corresponding string
if a case label is matched. If no case is matched, the default case is executed.
Using the Controle.WriteLine
function, we output the return value of the function.
using System;public class Program {// Main functionpublic static void Main(){// define function containng a switch expressionstatic string sports_i_like(string sport1, string sport2, string sport3)=> (sport1, sport2, sport3) switch{//matches if Cricket, Football, and Swimming given as input("Cricket", "Football", "Swimming") => "I like Cricket, Football, and Swimming.",//matches if Cricket, Football, and Baseball given as input("Cricket", "Football", "Baseball") => "I like Cricket, Football, and Baseball.",//matches if Hockey, Football, and Swimming given as input("Hockey", "Football", "Swimming") => "I like Hockey, Football, and Swimming.",//matches if Table Tennis, Football, and Swimming given as input("Table Tennis", "Football", "Swimming") => "I like Table Tennis, Football and Swimming.",//Default case(_, _, _) => "Invalid input!"};Console.WriteLine(sports_i_like("Cricket", "Football", "Swimming"));Console.WriteLine(sports_i_like("Cricket", "Football", "Racing"));}}
The input of the program is as follows, as the first call matches the first case label and the second call results in the default case:
I like Cricket, Football, and Swimming.
Invalid input.
Note that
Racing
is not part of any case label.
Free Resources