1

I am seeking a better and correct way of initializing Objects which is listed in another object? For example let's say I have two Classes Player and Team and one of properties in the Team class is a generic list of Player as

public List<Player>  Players{ get; set; } 

How I can Initialize the Player inside initializing the Team? I mean let's assume I do not have any object for Player and want to created them while creating/initializing the Team class object

void Main()
{

}

public class Player
{
    public string Name { get; set; } = string.Empty;
    public Player(){
        Name  = string.Empty;
    }
}

public class Team
{
    public string Name { get; set; } 
    public List<Player>  Players{ get; set; } 
    public Team(){
        Name = string.Empty;
        Players = new List<Player>();
    }
}
1
  • 1
    How about passing an IEnumerable<Player> to the Team() constructor that it can use to populate the list? Commented Nov 15, 2019 at 14:32

5 Answers 5

3

You can initialize your variable in the constructor:

public class Team
{
    public string Name { get; set; }
    public List<Player> Players { get; set; } 

    public Team()
    {
        Name = string.Empty;
        Players = new List<Player>()
        {
            new Player() { Name = "A"},
            new Player() { Name = "B"},
            new Player() { Name = "C"}
        };
    }
}

Or you can use a language feature from C# 6.0 called auto-property initializers:

public class Team
{
    public string Name { get; set; } = string.Empty;
    public List<Player> Players { get; set; } = new List<Player>()
    {
        new Player() { Name = "A"},
        new Player() { Name = "B"},
        new Player() { Name = "C"}
    };
}

The difference is only in the syntax. Both ways will result in the same program being executed.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Eiver, but where exactly is this happening? in Team constructor? or in Team Property declaration?
You can do it either way. I updated my answer to make it more clear.
2

Do you just mean this:

public Team(){
    Name = string.Empty;
    Players = new List<Player> {
        new Player(), new Player() //etc
   };
}

if you had a list of names for each player you could pass them into the Team constructor (or create an overload) as follows:

public Team(IEnumerable<string> playerNames){
    Name = string.Empty;
    Players = new List<Player>();
    foreach(var player in playerNames {
        Players.Add(new Player { Name = player});
   };
}

2 Comments

Thanks for reply Tim but are the Player() constructor of Player ? in that case why not using the Name Property?
you'd have to set the names to something, do you have a list of names for each player?
1

Based on the code you have, an instantiated Team has an empty list of players. To add a player to that list, simply add an instantiated Player to the list, just like you would do for any List<T>.

var myTeam = new Team();
var myPlayer = new Player();

myTeam.Players.Add(myPlayer);

If you want to do this during the initialization of the Team, the same approach applies:

public class Team
{
    // ...

    public Team()
    {
        Players = new List<Player>();

        this.Players.Add(new Player());
        this.Players.Add(new Player());
    }
}

You can also do this in one line:

public class Team
{
    // ...

    public Team()
    {
        Players = new List<Player>() 
        { 
            new Player(), 
            new Player() 
        };
    }
}

Presumably, you would want to receive these players via a constructor parameter? If so, then add the constructor parameter instead of directly instantiating new players:

public class Team
{
    // ...

    public Team(IEnumerable<Player> players)
    {
        Players = new List<Player>(players);
    }
}

Note that this code makes a new list (with the same objects in it), rather than using the collection object that was passed into the constructor.

Comments

1

If you want to inialize Players while initializing the team, you can just take a List of Players as the parameter for Team's constructor, like this:

    public Team(List<Player> players)
    {
        Players = players;
    }

and then call it this way:

var team = new Team(new List<Player>() { new Player("name1"), new Player("name2") });

You might as well take a more abstract collection as Type for constructor parameter, like IEnumerable, this will allow you to pass other collections at initialization:

    public Team(IEnumerable<Player> players)
    {
        Players = players;
    }

The final code would look like this:

class Program
{
    static void Main(string[] args)
    {
        var team = new Team("Juventus",
            new List<Player>
            {
                new Player("Ronaldo"), 
                new Player("Messi")
            });
    }
}

public class Player
{
    public string Name { get; set; }
    public Player(string name)
    {
        Name = name;
    }
}

public class Team
{
    public string Name { get; set; }
    public IEnumerable<Player> Players { get; set; }
    public Team(string name, IEnumerable<Player> players)
    {
        Name = name;
        Players = players;
    }
}

2 Comments

You're passing Players in and then ignoring it - also coding convention is the parameter should be players
Just a typo, my bad
0

If you meant that you want to have a default list of players initialized already in every Team ojbect, you clould use this syntax:

public class Team
{
    public string Name { get; set; } = string.Empty;
    public IEnumerable<Player> Players { get; set; } = new List<Player>();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.