0 votes
in Dot Net by
Positional patterns in C#

1 Answer

0 votes
by

Some types include a Deconstruct method that deconstructs its properties into discrete variables. When a Deconstruct method is accessible, you can use positional patterns to inspect properties of the object and use those properties for a pattern. Consider the following Point class that includes a Deconstruct method to create discrete variables for X and Y:

public class Point

{

    public int X { get; }

    public int Y { get; }

    public Point(int x, int y) => (X, Y) = (x, y);

    public void Deconstruct(out int x, out int y) =>

        (x, y) = (X, Y);

}

Additionally, consider the following enum that represents various positions of a quadrant:

public enum Quadrant

{

    Unknown,

    Origin,

    One,

    Two,

    Three,

    Four,

    OnBorder

}

he following method uses the positional pattern to extract the values of x and y. Then, it uses a when clause to determine the Quadrant of the point:

...