O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Array Initializers

Sometimes arrays have to be prepopulated with elements. To make this easier, a different form of array creation expression exists:

int[] squares = new int[] { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };

Here the length of the array is inferred from the number of expressions in the initializer list. If you specify the length between the square brackets, the number of elements that are provided must match.

In fact, the syntax can be abbreviated. Notice the redundancy in saying the type of the elements multiple times here. A shorter notation, using an implicitly typed array creation expression, is as follows:

int[] squares = new [] { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };

Or even:

int[] squares = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required