2.6.8 Creating Contained Objects in a Constructor

Creating Contained Objects in a Constructor

Team receives its captain but creates its own roster list. That keeps list allocation and the initial captain registration inside the class that manages the roster.

Put owned setup inside Team

Use the Player from the parameterized-constructor lesson and supply a non-null captain.

Soccer example
using System.Collections.Generic;

public class Team
{
    private Player captain;
    private List<Player> players;

    public Team(Player captain)
    {
        this.captain = captain;
        this.players = new List<Player>();
        this.players.Add(captain);
    }

    public int GetPlayerCount()
    {
        return this.players.Count;
    }
}

The list field initially contains null. The constructor must create the list before calling Add. The Add call stores the same Player reference supplied as captain.

Count objects rather than references
Caller method
Player jordan = new Player("Jordan", 7);
Team wildcats = new Team(jordan);
int count = wildcats.GetPlayerCount();
Objects created by these statements
Type Number
Player 1
Team 1
List of Player references 1

count is 1. Neither assigning captain nor adding that reference to the list creates a second Player.

Apply the idea
Check your understanding