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?
[..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.Since this is passed to a parameter expecting
int[],[..h]represents anint[]. 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
hcontains the numbers 1 to 9, this is basically[1,2,3,4,5,6,7,8,9], though since aHashSetis 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:So
[..h]is rather a odd use of collection expressions. It would be more readable to useh.ToArray()instead.