I'm getting a stack overflow from using the get/set part of my index. I've tried putting the values into a list instead in the get set but with bad results.
class TrackList : CollectionBase
{
public Tracks this[int i]
{
get
{
return this[i];
}
set
{
this[i] = value;
}
}
}
Main:
class Program
{
public static void Main(string[] args)
{
TrackList l1 = new TrackList();
l1[0] = new Tracks(1, "Random");
l1[1] = new Tracks(2, "Random");
l1[2] = new Tracks(3, "Random");
}
}
Answer: I was looping inside my get/set. Here is the working code:
class TrackList : CollectionBase
{
public Tracks this[int i]
{
get
{
return (Tracks) List[i];
}
set
{
List[i] = value;
}
}
}
Main:
class Program
{
public static void Main(string[] args)
{
TrackList l1 = new TrackList();
l1.Add(new Tracks(1, "random"));
l1.Add(new Tracks(2, "random"));
l1.Add(new Tracks(3, "random"));
}
}
You are recursively calling the property indexer an infinite number of times. I think you want this:
Then, add your items:
Then replace an item using the indexer:
Or retrieve an item using the indexer:
Trying to use
l1[i]
wherei <= l1.Count
will produce anArgumentOutOfRangeException
, as you would expect.