C
C#2mo ago
Faker

{} vs [] when initializing an array in C#

Hello guys, is there a difference when we use {} to initialize an array or if we use [] ? I read that the [] is known as a collection expression.
C#

string[] orders = {"B123", "C234", "A345", "C15", "B177", "G3003", "C235", "B179"};

vs

string[] orders = ["B123", "C234", "A345", "C15", "B177", "G3003", "C235", "B179"];
C#

string[] orders = {"B123", "C234", "A345", "C15", "B177", "G3003", "C235", "B179"};

vs

string[] orders = ["B123", "C234", "A345", "C15", "B177", "G3003", "C235", "B179"];
12 Replies
Jimmacle
Jimmacle2mo ago
the second one is a newer way to do it, but they do the same thing in these examples the [] way can be used with lists and other collection types as well
Faker
FakerOP2mo ago
yep I see, it's better to just stick with the newer syntax?
Jimmacle
Jimmacle2mo ago
it doesn't really matter, but if you want to be consistent then the newer syntax can be used in more places
Faker
FakerOP2mo ago
ok noted, ty Hi, what do you mean by [] can be use with lists and other collection pls. I try to declare and initialize an array on the same line, like this: int [] arr = new int[] {1,2,3}; Here, we can't use the [] syntax? (I got an error while doing so)
Jimmacle
Jimmacle2mo ago
int[] arr = [1, 2, 3];
Faker
FakerOP2mo ago
yeah, is there a reason do use something like this: int [] arr = new int[] {1,2,3}; I saw that somewhere but don't remember where
Jimmacle
Jimmacle2mo ago
it's just a different way of creating an array it's using a collection initializer instead of a collection expression
Faker
FakerOP2mo ago
ah ok, in a collection initializer, we can't use the [] syntax, right ?
Jimmacle
Jimmacle2mo ago
that wouldn't be a collection initializer
Faker
FakerOP2mo ago
ahhh [] is used only for collection expression
Jimmacle
Jimmacle2mo ago
right
Faker
FakerOP2mo ago
It's clearer now, thanks !!

Did you find this page helpful?