In Javascript ES6, you are able to destructure arrays like this:
const [a,b,...rest] = someArray;
where a
is the first element
In C# you will need to write your own, like this one I'm using:
public static class ArrayExtensions
{
public static void Deconstruct<T>(this T[] array, out T first, out T[] rest)
{
first = array.Length > 0 ? array[0] : default(T);
rest = array.Skip(1).ToArray();
}
public static void Deconstruct<T>(this T[] array, out T first, out T second, out T[] rest)
=> (first, (second, rest)) = array;
public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T[] rest)
=> (first, second, (third, rest)) = array;
public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T fourth, out T[] rest)
=> (first, second, third, (fourth, rest)) = array;
public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T fourth, out T fifth, out T[] rest)
=> (first, second, third, fourth, (fifth, rest)) = array;
// .. etc.
}
Then simply do:
var (first, second,_ , rest) = new[] { 1, 2, 3, 4 }
Really quick: No.
C# does not support destructuring for Arrays yet.
Currently, I cannot find any information of this on the roadmap, either. Seems like there will be a lot of waiting involved until we get this syntactic sugar by default.
As @Nekeniehl added in the comments, it can be implemented though: gist.github.com/waf/280152ab42aa92a85b79d6dbc812e68a