Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are arrays only allowed in certain places?

Tags:

arrays

c#

As I understand it, C# has a syntax for writing arrays as such: { 1, 2, 3 }. Why is this invalid:

 x = { 1, 2, 3 }.GetLength(0);

while this is valid?

 int[] numbers = { 1, 2, 3 };
 x = numbers.GetLength(0);

Isn't the datatype of the expression { 1, 2, 3 } the same as numbers?

like image 230
Joe Avatar asked Dec 02 '22 19:12

Joe


2 Answers

Arrays are allowed anywhere - but you can only use that particular syntax (which is called an array initializer for creating them as part of a variable declaration - or as part of a larger expression called an array creation expression.

You can still create them though:

x = new int[] { 1, 2, 3 }.GetLength(0);

So within that, new int[] { 1, 2, 3 } is the array creation expression, and the { 1, 2, 3 } part is the array initializer.

Array creation expressions are described in section 7.6.10.4 of the C# 5 spec, and array initializers are described in section 12.6.

like image 150
Jon Skeet Avatar answered Dec 04 '22 08:12

Jon Skeet


The syntax you refer to is an object collection initializer. It is useful when initializing an instance of different types. It does not, in itself, create an instance of a given type.

For instance, you can use it to declare arrays:

int[] nums = new int[] { 1, 2, 3 };

Lists:

List<int> nums = new List<int> { 1, 2, 3 };

Dictionary:

Dictionary<string, int> pairs = { { "One", 1 }, { "Two", 2 }, { "Three", 3 } };

You can still inline things to achieve your initial intention with a little more code:

new[] { 1, 2, 3 }.GetLength(0);
like image 42
Justin Niessner Avatar answered Dec 04 '22 09:12

Justin Niessner