Search code examples
c#.net-7.0

Passing .. operator to array


Can I define .. as named array in list pattern without additional slices?

Something like

string s[] = {"<=","some","text","=>"}

if (s is ["<=",..{Length: >1} AS string[] subarray, "=>"])
  Console.WriteLine(string.Join('\n', subarray));
else 
  Console.WriteLine("ERROR");

Solution

  • Your code is something like the compiling and functioning,

    This code uses a C# 11 list pattern to assert the first and last values of a sequence and captures the slice pattern .., for the 0 to many items in between to a new variable. Then a property pattern, checks the Length of the captured array, finally assigning the capture to subString.

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            string[] s = new[] {
                "<=",
                "some",
                "text",
                "=>"
            };
            
            if(s is ["<=",  .. string[] {Length: > 0} subString, "=>"])
            {
                Console.WriteLine(string.Join('\n', subString));
            }
            else
            {
                Console.WriteLine("ERROR");
            };
        }
    }