Why in certain places only arrays are allowed?

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

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

is it really so far?

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

Is the data type of the expression { 1, 2, 3 } same as the numbers type?

+4
source share
3 answers

The syntax you are referencing is the initializer of the object collection. This is useful when initializing an instance of different types. It by itself does not create an instance of a certain type.

For example, 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 embed things to achieve your original intent with a little code:

 new[] { 1, 2, 3 }.GetLength(0); 
+7
source

Arrays are allowed anywhere, but you can only use this special syntax (called the array initializer to create it as part of the variable declaration) or as part of a larger expression called the array creation expression.

You can still create them:

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

Thus, new int[] { 1, 2, 3 } is an expression for creating an array, and part { 1, 2, 3 } is an array initializer.

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

+9
source

x = new[] { 1, 2, 3 }.GetLength(0); will provide you with what you want, since {1, 2, 3} not a native array, but rather an array initializer. And GetLength() works with the first, but not the last.

+2
source

Source: https://habr.com/ru/post/1481268/


All Articles