Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference in List initialization

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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};

turns into

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading