what is the difference between this to List initialization in C#:
List<int> list = [];
List<int> list = new List<int>();
Are those two lines doing the exact same thing?
I can’t find any source, web page, documentation mentioning it. Chat-GPT is insisting that first line will not work and is not correct, but it works for me.
Maybe there is a difference?
>Solution :
List<int> list1 = [];
List<int> list2 = new List<int>();
Will be treated by the compiler as the same thing. This is all just syntactic sugar.
The difference is when you change the type of the variable you’re assigning it to.
IEnumerable<int> list = []; // [] is "Array.Empty<int>()"
ICollection<int> list = []; // [] is "new List<int>()"
HashSet<int> list = []; // [] is "new HashSet<int>()"
int[] list = []; // [] is "Array.Empty<int>()"
IReadOnlyList<int> list = []; // [] is "Array.Empty<int>()", and makes me chuckle
Now, if we’re NOT talking about assigning an empty collection, then things get different.
List<int> list1 = [1,2,3];
List<int> list3 = new List<int>() {1,2,3};
List<int> list = new List<int>();
CollectionsMarshal.SetCount(list, 3);
Span<int> span = CollectionsMarshal.AsSpan(list);
int num = 0;
span[num] = 1;
num++;
span[num] = 2;
num++;
span[num] = 3;
num++;
List<int> list2 = new List<int>();
list2.Add(1);
list2.Add(2);
list2.Add(3);
When [] is assigned to an array, the compiled code will still remain the same. There will be differences under the hood depending on the target type, even if [] is treated as an array. Use https://sharplab.io (or another decompiler) to find out what really happens in your situation.