In C#, pattern matching is used to determine if a variable is of a certain type and/or holds a particular value or not.
Pattern matching was originally introduced in #7.0, and additional features were added to it in C# 8.0.
is
patternThe most basic type of pattern matching is implemented using the is
pattern. The is
pattern tests the data type and value of the variable in question. It is usually incorporated in an if
statement, which returns true
if the pattern is matched and false
otherwise.
Subsequently, the user can choose to discard the value according to the value returned by this if
statement.
The following program demonstrates how to use the if
pattern.
In the main program, we declare a variable of type int
and value 110
. Using an if statement and the is
pattern, the program checks if the data-type of this variable is int
and if its value is greater than 100.
using System;public class Program {// Main functionpublic static void Main(){// variable to be checkedint sample = 110;// if statement that checks if value of sample is of type int and greater than 100if (sample is int count && count > 100){//output if condition is trueConsole.WriteLine("The value of sample, " + sample + ", is of type int and grater than 100");}else{//output if condition is falseConsole.WriteLine("The value of the variable sample is not of our desired type and/or value");}}}
If these conditions are met, the program outputs the following string:
The value of sample, 110, is of type int and greater than 100
Otherwise (for, let’s say, sample = 99), the following string is printed:
The value of the variable sample is not of our desired type and/or value
case
patternSimilarly, pattern matching can be performed using the case
statements. The following program implements a case
statement to check if the value of a variable input
is null
or not:
switch (input)
{
case null:
Console.WriteLine("Value is null, terminate!")
default:
Console.WriteLine("Value is not null, you may proceed!")
}
Relational patterns are used to compare the value of a variable with constants.
For example, the following function compares the value of weight
to cut-off values provided by the user and returns the corresponding string:
string check(int weight) =>
weight switch
{
(> 60) and (< 70) => "Normal",
< 60 => "Underweight",
> 80 => "Overweight",
};
Similarly, pattern matching can be used to verify if the data type of a variable or data structure is as required:
if (sequence is List<T> list)
{
return list[list.Count];
}
This check comes in handy in the example above, as it returns the number of variables in the list
. If list
was not of type List<T>
, for instance of type int
instead, it would be impossible to calculate its length.
Free Resources