Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly typed arrays: why we can't set array size explicitly?

Tags:

c#

The C# language specification (7.6.10.4) says, that there are tree kinds of array creation expressions:

new non-array-type [ expression-list ] rank-specifiersopt array-initializeropt
new array-type array-initializer
new rank-specifier array-initializer

The third one is intended for implicitly typed arrays:

var foo = new[] { 1, 2, 3 };

The question: is there any weighty reason to forbid to set array size explicitly in case of implicitly typed array?

It looks like asymmetric behavior, comparing with this syntax:

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

Update.

A little clarification. The only advantage for combination of explicitly set array size and array initializer I can see, is the compile-time check for initializer length. If I've declared the array of three ints, the initializer must contain three ints.

I think, the same advantage is true for the implicitly typed arrays. Of course, to use this advantage or not to use is the personal preference.

like image 346
Dennis Avatar asked Jan 30 '13 05:01

Dennis


1 Answers

The rank specifier is not needed because it is already supplied by the number of elements in the initialization list.

like image 121
andy Avatar answered Oct 23 '22 19:10

andy