Home > Software engineering >  Passing .. operator to array
Passing .. operator to array

Time:12-19

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");

CodePudding user response:

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");
        };
    }
}
  • Related