Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading