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

Collection Initializers

When arrays were introduced in Chapter 4, “Language Essentials,” you saw the use of array initializer expressions to create an array and initialize its elements in one operation:

int[] primes = new int[4] { 2, 3, 5, 7 };

Recall that various kinds of type inference can be used to simplify the preceding declaration and initialization, even all the way down to the following:

var primes = new [] { 2, 3, 5, 7 };

What’s of more relevance here is the use of an initializer list delineated by curly braces to supply the array’s elements. You’ll agree that’s way more handy than having to write the following:

int[] primes = new int[4];primes[0] = 2;primes[1] = 3;primes[2] = 5;primes[3] = 7;

Although arrays are very useful constructs, ...

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