Question

Different between Curly braces{} and brackets[] while initializing array in C#?

I am really curious to know what is the different between these lines?

//with curly braces
int[] array2 = { 1, 2, 3, 4, };
//with brackets
int[] array3 = [1, 2, 3, 4,];

Console.WriteLine(array2[1]);
Console.WriteLine(array3[1]);

//the output is the same.

I want to know what is the different between using curly braces and brackets while initializing values.

 8  797  8
1 Jan 1970

Solution

 17

In the example you've given, they mean the same thing. But collection expressions are in general more flexible. In particular:

  • They can create instances of collections other than arrays
  • They can use the spread operator to include sequences

For example:

ImmutableList<int> x = [0, .. Enumerable.Range(100, 5), 200];

That creates an immutable list of integers with values 0, 100, 101, 102, 103, 104, 200.

Note that while collection initializers can also be used to initialize non-array collection types in a somewhat flexible way, they're more limited than collection expressions and still require the new part. So for example:

// Valid
List<int> x = new() { 1, 2, 3 };

// Not valid
List<int> x = { 1, 2, 3 };

// Not valid (collection initializers assume mutability)
ImmutableList<int> x = new() { 1, 2, 3 };

Collection expressions address both of these concerns.

2024-07-24
Jon Skeet