Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare an implicitly typed array without an initializer?

Tags:

arrays

c#

Why do I have to write int after new when I am declaring the array num without an initializer? E.g.

int[] num = new int[5];

For another array, num1, I just declared it first and then gave it values, and I didn't type int after new like I did for array num.

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

Why does this shortcut not work for my first example?

like image 335
elseshawe Avatar asked Sep 28 '17 15:09

elseshawe


3 Answers

The "full" syntax for declaring an array with values is new int[] {1, 2, 3, 4};.

Your new [] {1, 2, 3, 4}; line is a shorthand syntax. It's an "implicitly typed" array. Because the values are all int, the array is automatically declared an int[].

The reason you can't also write int[] x = new [5]; is simply that this feature has not been implemented by the C# designers.

like image 192
Blorgbeard Avatar answered Nov 20 '22 20:11

Blorgbeard


The type of the array can be inferred (under certain circumstances, which your example fullfills) if you provide the values for the array. Since the values are all integers, the compiler is able to infer that you want an array of integers. If you don't provide any values (or if the values aren't all implicitly convertible to the type of one of the values), it has no way of inferring what the type of the array should be, and so you need to specify it explicitly.

like image 45
Servy Avatar answered Nov 20 '22 19:11

Servy


Because you seem to expect that the way the compiler infers the type of the array is somehow based on the type to the left of the assignment operator:

int[] num = new[5];

Your thought process is:

  1. num is an array of ints.
  2. new[5] is an array of something.
  3. something has to be int because that is num's type.

That is not the way the compiler works. The compiler must figure out univocally the type to the right of the assignment expression and once it does, it will check if the assignment to whatever is on the left is valid.

In the syntaxes allowed in C#, the compiler always has enough information to figure out the type on the right side of the assignment (if it has any). Your proposed syntax wouldn't provide that information.

like image 3
InBetween Avatar answered Nov 20 '22 18:11

InBetween