Time for action – adding ponies using a Collection Initializer
If we know the items to add ahead of time, we can add them when we create the List
or Dictionary
.
Modify
LearningScript
as shown in the next screenshot.Save the file.
In Unity, click on Play.
What just happened?
Here's the Console output:
The analysis of the code is as follows:
The code on lines 8 and 9 with its description:
List<string> myFavoritePonies = new List<string>() {"Princess Cadence", Fluttershy"};
This is actually a single statement. It's on two lines to make it fit the screenshot.
Line 9 shows the Collection Initializer that's been added to the usual
List
declaration.Notice the pony names are between two curly braces. This is not a code block. This is another use of curly braces.
This
List
Collection Initializer is the two curly braces and the strings, the pony names, that are between them.Notice there is a semicolon after the last curly brace. This ends the
List
declaration statement.The code between lines...