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.
In the example you've given, they mean the same thing. But collection expressions are in general more flexible. In particular:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With