C# – How to Differentiate Between Curly Braces {} and Brackets [] When Initializing Arrays in C#

.netc++

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.

Best Answer

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.