Answer the question
In order to leave comments, you need to log in
Is it possible to make indexers dynamic length?
using System; // 1
using System.Collections.Generic; // 2
namespace test_for_fun
{
class Program
{
static void Main()
{
People people = new People();
people[0] = new Person { Name = "Tom" };
people[1] = new Person { Name = "Bob" };
people[2] = new Person { Name = "Jon" };
}
}
class Person
{
public string Name { get; set; }
}
class People
{
Person[] data;
public People()
{
data = new Person[2];
}
public Person this[int index]
{
get
{
return data[index];
}
set
{
if (data.Length < index) // 37
{
//увеличить длину data
}
data[index] = value;
} // 42
}
}
}
Answer the question
In order to leave comments, you need to log in
class People{
List<Person> data = new List<Person>();
...
but as soon as I write this line (people[2] = new Person { Name = "Jon" };), then in debugging the process immediately jumps to line 42, skipping 37.
Длинна(2) < Индекса(2)
- no, it is not at all less, we do not go into the conditions. Why I couldn't figure it out in debugging I don't understand.
public Person this[int index]
{
get { return data[index]; }
set
{
if(data.Length <= index) // 37
{
Array.Resize(ref data, index + 1);
}
data[index] = value;
} // 42
}
It feels like you need Dictionary<int, Person>
, instead of an array, then you won't need to dynamically expand the array when you need it (and it won't create extra empty space if you want to skip a couple of hundred elements)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question