user195597
user195597

Reputation:

C# Dynamic size indexers

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; }
    }
}

Upvotes: 1

Views: 422

Answers (2)

Konamiman
Konamiman

Reputation: 50273

If i use List ,then there is no point to have indexers

Why? You can still using indexes with lists, and you can define the initial capacity of the list at construction time. See here: http://msdn.microsoft.com/en-us/library/d0cyc8ex.aspx

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500675

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.Resize will 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...

Upvotes: 4

Related Questions