In C# 8.0, positional pattern matching is used to determine whether or not a deconstructed variable, usually contained in a struct
, matches a user-defined nested pattern.
The Deconstruct method is used to split a variable, such as the tuple
type, into two or more independent variables. Without deconstruction, it may not be possible to apply positional pattern matching on variables that consist of more than 1 value.
Although pattern matching was made available in C# 7.0, positional pattern matching is only available in C# 8.0 and above.
The following program declares a struct named coordinates
. The constructor of this struct takes in 2 values, the X and Y coordinates of a point, as its parameters and stores It as a tuple.
The Deconstruct
method of the struct splits the tuple into two independent variables.
In the Main
function, we declare a static local function to identify if the aforementioned tuple, when deconstructed, follows a pattern. This is done using switch-statements, which return the corresponding string
value if a condition is met.
using System;// declares struct with a single variable named Xpublic readonly struct coordinates{public int X { get; }public int Y { get; }// constructor for the structpublic coordinates(int x, int y) => (X,Y) = (x,y);// deconstructor to store each value in a separate// variable in the case of more than one values, such as a tuplepublic void Deconstruct(out int x, out int y) => (x,y) = (X,Y);}public class Program {// Main functionpublic static void Main(){// local static function to determine which pattern existsstatic string identify_pattern(coordinates sample) => sample switch{// switchs statement that return corresponding return valuescoordinates (1,1) => "Point lies in the first quadrant of cartesian plane.",coordinates (-1,1) => "Point lies in the second quadrant of cartesian plane.",coordinates (-1,-1) => "Point lies in the third quadrant of cartesian plane.",coordinates (1,-1) => "Point lies in the fourth quadrant of cartesian plane.",_ => "Hmm, I am not sure about this point. You will have to plot it and find out!",};// declaring an instance of our structcoordinates sample = new coordinates(-1,1);// calling indentify_pattern and printing its return valueConsole.WriteLine(identify_pattern (sample));}}
If the value of X and Y is -1 and 1, respectively, the following output is returned:
Point lies in the second quadrant of the cartesian plane.
If the value of X and Y does not match any switch condition, the return value is:
Hmm, I am not sure about this point. You will have to plot it and find out!
Free Resources