Ice725 Posted March 25, 2006 Posted March 25, 2006 (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 March 25, 2006 by Ice725 Quote
Cags Posted March 25, 2006 Posted March 25, 2006 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. Quote Anybody looking for a graduate programmer (Midlands, England)?
Ice725 Posted March 25, 2006 Author Posted March 25, 2006 Thanks for the tip, I'll look into strongly typed collections. Quote
Ice725 Posted March 25, 2006 Author Posted March 25, 2006 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? Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.