Dennis
Dennis

Reputation: 37780

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

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.

Upvotes: 13

Views: 2320

Answers (2)

JLRishe
JLRishe

Reputation: 101738

I think one difference here is that this syntax can be seen as first creating a typed array, and then populating it:

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

This is similar to the way we can declare and initialize other datatypes in a single statement:

var list = new List<string>{ "a", "b", "c" };
var dict = new Dictionary<string, string>{ {"a", "b"}, {"c", "d"} };

The first statement creates and int[3] and populates it. The second and third statements create a List<string> or Dictionary<string, string> and populate them.

But if you do this:

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

this is not the same thing. There is no such datatype as a [3], so unlike the other 2 examples, this isn't a case of first creating a specific object and populating it. This is a special syntax for creating implicitly-typed arrays, where the array and its contents are inferred from the contents of the braces, and then created.

I don't know enough to say why that kind of syntax shouldn't exist, but I think this is a plausible explanation for what you see as an asymmetry.

Upvotes: 0

Related Questions