I need some help with an Indexer on a class I wrote. For simplicity, let's say the class is called Team. Some of the properties of team class are Name and City and Color. I have another class called Player, with Properties of Name, Position, and Height.
Within my Team class, I have an indexer as follows.
So if I'd like to get a player's name, I can do the following code:
This is working fine, but I'd like to make it a bit more like some of the controls in the .NET framework. For instance, if you want the first item in a ListBox, the code is listBox1.Items[0], how can I make my Team class have a property called Players, so my code could read like this:
NOTE: I am filling the Player[] array within the Team class. I've created an indexer like public Player this[index] { } within the Player class, but this seems to be a dead-end because the _player array resides in the Team class. Can someone point me in the correction direction?
Within my Team class, I have an indexer as follows.
Code:
class Team
{
private Player[] _players;
public Player this[index]
{
get
{
return _players[index];
}
}
}
So if I'd like to get a player's name, I can do the following code:
Code:
Team team = new Team(id);
string playername = team[0].Name;
This is working fine, but I'd like to make it a bit more like some of the controls in the .NET framework. For instance, if you want the first item in a ListBox, the code is listBox1.Items[0], how can I make my Team class have a property called Players, so my code could read like this:
Code:
string playername = team.Players[0].Name;
NOTE: I am filling the Player[] array within the Team class. I've created an indexer like public Player this[index] { } within the Player class, but this seems to be a dead-end because the _player array resides in the Team class. Can someone point me in the correction direction?
Last edited: