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?
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.
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.
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:
num
is an array of int
s.new[5]
is an array of something.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With