Array Indexer

Ice725

Freshman
Joined
Apr 19, 2004
Messages
31
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.

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:
Essentailly the Items property is a public property of a collection class. To-do this yourself you need to create a strongly typed PlayerCollection class (which will implement an indexer etc. Then you add a property such as
C#:
private PlayerCollection _players;
public PlayerCollection Players
{
get { return _players; }
set { _players = value; }
}
If you need help creating a strongly typed collection just ask, but as a starting pointer you can do it by inheriting CollectionBase.
 
I've created a class called PlayerCollection, which implements CollectionBase.

But I'm not sure how to code the Team class now. After I createa new instance of Team, I am not seeing any properties displayed in intellisense. Could you assist me with this part?
 
Back
Top