What is positional pattern matching in C# 8.0?

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.

Example

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 X
public readonly struct coordinates
{
public int X { get; }
public int Y { get; }
// constructor for the struct
public 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 tuple
public void Deconstruct(out int x, out int y) => (x,y) = (X,Y);
}
public class Program {
// Main function
public static void Main()
{
// local static function to determine which pattern exists
static string identify_pattern(coordinates sample) => sample switch
{
// switchs statement that return corresponding return values
coordinates (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 struct
coordinates sample = new coordinates(-1,1);
// calling indentify_pattern and printing its return value
Console.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

Copyright ©2025 Educative, Inc. All rights reserved