Get an Array from HashSet in c# with operator [..]

Advertisements

Are these range operator and indexer? I have never seen them used like this [..h].
Line 6 in this code:

public static void Main(string[] args)
{
    int[] a ={1,2,3,4,5,6,7,8,9};
    HashSet<int> h=new(a);
        /// do somethings on HashSet
    WriteArray([..h]);
}

static void WriteArray(int[] a)
{
    foreach(var n in a)
    {
        Console.Write($"{n} ");
    }
}

What operator are used in [..h] ?
Can you recommend a reference to study these operators or the method used?

>Solution :

[..h] is a collection expression, basically a concise syntax to create collections, arrays, and spans. The things inside the [ and ] are the collection’s elements, e.g.

List<int> x = [1,2,3];
// basically:
// var x = new List<int> { 1,2,3 };

Since this is passed to a parameter expecting int[], [..h] represents an int[]. What does this array contain then? What is ..h? In a collection expression, .. can be prefixed to another collection to "spread" that collection’s elements.

Since h contains the numbers 1 to 9, this is basically [1,2,3,4,5,6,7,8,9], though since a HashSet is not ordered, the order of the elements may be different.

Usually .. is used when there are other elements/collections you want to put in the collection expression, as the example from the documentation shows:

string[] vowels = ["a", "e", "i", "o", "u"];
string[] consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
                       "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"];
string[] alphabet = [.. vowels, .. consonants, "y"];

So [..h] is rather a odd use of collection expressions. It would be more readable to use h.ToArray() instead.

Leave a ReplyCancel reply