Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created August 3, 2023 16:33
Show Gist options
  • Save davepcallan/e2864d501588e4b44055b4be751c8eca to your computer and use it in GitHub Desktop.
Save davepcallan/e2864d501588e4b44055b4be751c8eca to your computer and use it in GitHub Desktop.
C# 11 List Pattern Examples
namespace ListPatterns
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4};
Console.WriteLine("constant and relational patterns");
Console.WriteLine(numbers is [1, 2, 3, 4]); // True as exact match
Console.WriteLine(numbers is [1, 2, 3]); // False as length is wrong
Console.WriteLine(numbers is [1, 2, 3, 4, 5]); // False as length is wrong
Console.WriteLine(numbers is [0 or 1, <= 2, >= 3, >= 3]); // True as first element is 1,
// second element is less than or equal to 2,
// third element is greater than or equal to 3 and
// fourth element is greater than or equal to 3
Console.WriteLine(string.Empty);
Console.WriteLine("discard patterns");
Console.WriteLine(numbers is [1, 2, _, 4]); // true as position 1, 2, 4 are matching
Console.WriteLine(numbers is [1, 2, 3, _]); // true as position 1,2,3 are matching
Console.WriteLine(numbers is [1, _, _, 4]); // true as position 1 and 4 are matching
Console.WriteLine(numbers is [1, _, _, 4, _]); // false as length is not matching
Console.WriteLine(numbers is [_]);
Console.WriteLine(string.Empty);
Console.WriteLine("range patterns");
Console.WriteLine(numbers is [.., 4]); // true as 4 is last element
Console.WriteLine(numbers is [1, ..]); // true as 1 is first element
Console.WriteLine(numbers is [1, .., 4]); // true as the range is from 1 - 4
Console.WriteLine(numbers is [.., 4, _]); // false as 4 is not the 2nd last item
Console.WriteLine(string.Empty);
Console.WriteLine("var patterns");
if (numbers is [_,var secondNumber,..]){
Console.WriteLine($"The second number is {secondNumber }");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment