Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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.

 

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:

 

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:

 


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?

Edited by Ice725
Posted

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

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.

Anybody looking for a graduate programmer (Midlands, England)?
Posted

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?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...