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.

  1. Modify LearningScript as shown in the next screenshot.
  2. Save the file.
  3. In Unity, click on Play.
Time for action – adding ponies using a Collection Initializer

What just happened?

Here's the Console output:

What just happened?

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 14 and 15:
    Dictionary<int, string> ponyDictionary = new Dictionary<int, string>() {{10, "Nightmare Moon"}, {20, "Rainbow Dash"}};

    This is a single statement. It's on two lines to make it fit the screenshot.

    Line 15 shows the Collection Initializer that's been added to the usual Dictionary declaration.

    Each key and value pony name is between two curly braces, then all the key/value pair combinations being initialized are between two curly braces.

Pop quiz – understanding an array and a List

Q1. In an array or a List, what is an element?

Q2. In an array or a List, what is the index number of the first element?

Q3. Can a single array, or a single List, store different types of data?

Q4. How can you add more elements to an array to make room for more data?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.223