0

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?

3
  • [] is an array initializer and the .. is the list all operator. .., Arrays Commented Mar 10, 2024 at 9:15
  • Check out what is new in c# 12 Commented Mar 10, 2024 at 9:24
  • Thanks. I didn't know about list all operator Commented Mar 10, 2024 at 9:24

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.