Originally Posted by
stumon
That still wont work. Lets use a baseball game for example. A baseball game would be a class and it has Innings, so those innings would be a class with seperate methods to access the top or botton of the inning, with scores, etc. Well a baseball game would have more than 1 inning, so I want to use a List<Innings> variable (keeping it private), but I want that variable to have a public indexer.... so...
BaseBallClass game = new BaseBallClass();
game.Inning[1].TopOf();
game.Innine[1].BottomOf(int runs);
game.Inning[4].BottomOf();
Code:
public class BaseBallClass
{
private List<Innings> inning = new List<Innings>();
public Innings Inning // Here I want public Innings Inning[int index] but it wont work.
{
get { return inning[index]; } // make sure its within range.
set { inning.add(value); } // use the indexer for validation purposes.
}
}
public class Innings
{
private int topInningRuns;
private int bottomInningRuns;
public int TopOf
{
//get ; set ; here
}
}
I think I am beginning to see that this can not be done unless I use public variables. Unless someone else has any ideas?
No, here's what I'm suggesting:
Code:
public class BaseBallClass
{
private InningCollection innings = new InningCollection();
public InningCollection Innings
{
get { return innings; }
private set { } // only for your class's internal use
}
}
public class InningCollection // Probably want to implement IEnumerable here too
{
private List<Inning> innings = new List<Inning>();
public Inning this[int i]
{
get { return innings[i]; }
set { innings[i] = value; }
}
public void Add(Inning i)
{
innings.Add(i);
}
// Other stuff, like IEnumerable members, etc.
}
public class Inning
{
private int topInningRuns;
private int bottomInningRuns;
public int TopOf
{
//get ; set ; here
}
}
Then you could do this:
Code:
BaseBallClass game = new BaseBallClass();
game.Innings[2].TopOf = 5;
That works because game.Innings returns an InningCollection, and then [2] references the second Inning in the InningCollection.
By making InningCollection support IEnumerable you can even do things like:
Code:
foreach (Inning i in game.Innings)
{
}
Essentially, the main class has a property that returns a collection class, and the collection class is indexable, making effectively an indexed named property. This is used a lot in Windows Forms, for example:
listbox1.Items[0] -- .Items returns a collection object that can be indexed, iterated over, etc.
Yes, at first it seems like it adds a lot of overhead, it adds an additional class to the mix, but that class consists of code you'd already need -- code to index and iterate your collection -- and it keeps all that code in one place, separated from everything else.