How to set up indexer that are dynamically grown in size ?Down,i used the fixed size array.
If i use List<Employee> ,then there is no point to have indexers.so how can i keep the
array to grow dynamically?
class Department
{
private Employee[] employee = new Employee[6];
public Employee this[int arg]
{
get { return this.employee[arg]; }
set { this.employee[arg] = value; }
}
}
You’d have to create a new array if the index is bigger than the current size, and copy the existing contents into the new array.
Array.Resizewill do this for you. (Note that it doesn’t change the existing array – it returns you a new array of the specified size, containing the previous elements.)You may want to consider resizing to a larger array than you really need, just so that you don’t have to resize as often.
Are you sure it wouldn’t be easier just to use a
List<T>though? Doing this sort of thing manually is rather tedious when it’s built into the framework already…