{} 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.
12 Replies
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 wellyep I see, it's better to just stick with the newer syntax?
it doesn't really matter, but if you want to be consistent then the newer syntax can be used in more places
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)int[] arr = [1, 2, 3];
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 whereit's just a different way of creating an array
it's using a collection initializer instead of a collection expression
ah ok, in a collection initializer, we can't use the
[]
syntax, right ?that wouldn't be a collection initializer
ahhh
[]
is used only for collection expressionright
It's clearer now, thanks !!