Search code examples
c#.netcollectionspattern-matching

What is the difference between these patterns?


The pattern [] only matches empty lists, while [_] only matches lists with exactly one element ([_,_] for exactly two elements and so on).

So far it is logical for me.

But it seems the patterns [..] and [_, ..] and [.., _] are equivalent which is a bit counterintuitive for me.

The following code prints true 6 times:

    Console.WriteLine(new int[]{1} is [..]);        
    Console.WriteLine(new int[]{1} is [_, ..]);
    Console.WriteLine(new int[]{1} is [.., _]);
    
    Console.WriteLine(new int[]{1,2} is [..]);      
    Console.WriteLine(new int[]{1,2} is [_, ..]);
    Console.WriteLine(new int[]{1,2} is [.., _]);

Solution

  • List patterns documentation states that:

    A slice pattern matches zero or more elements. You can use at most one slice pattern in a list pattern. The slice pattern can only appear in a list pattern.

    And they are not doing the same, they just happen to do the same thing for the arrays you're using.

    [..] is always going to evaluate to true for not-null arrays.

    [_, ..] and [.., _] are always going to evaluate to true for all arrays that are not-null and contain at least one element.