PositiveGuy
PositiveGuy

Reputation: 47783

Helper to add to an Array

I'm trying to create this helper method and not sure how to handle the indexing on this. I keep getting index out of bounds when it hits the new class initializer in my helper:

public static void AddColumn(this ColumnElementType[] columnListToAddTo,
                             string name, string value)
{
    // Add a new column to the column list
    columnListToAddTo[columnListToAddTo.Length] = new ColumnElementType
            {
                 NAME = name,
                 VALUE = value
            };
}

Example setting up and using the helper:

        ColumnElementType[] columns =  new ColumnElementType[3];
        columns.AddColumn(Constants.EmailColumnName, email);
        columns.AddColumn(Constants.FirstNameColumnName, firstName);
        columns.AddColumn(Constants.LastNameColumnName, lastName);

Upvotes: 0

Views: 695

Answers (3)

M4N
M4N

Reputation: 96626

This doesn't work, since columnListToAddTo[columnListToAddTo.Length] will always return 3 (the length of the array you declared). Therefore:

  • you are trying to add each element at an invalid index (3; valid would be 0..2)
  • even if you use Length-1, you would always put the new element at the same array location (overwriting the reference to the previously added element)

Also, since an array cannot be extended (you'd have to copy the contents to a new, larger array), I would also suggest to use a List<ColumnElementType> or alternatively an ArrayList (if you can't use generics).

If you still want to use an array, then you should extend your helper method to take an index parameter, where to add the new element, e.g:

ColumnElementType[] columns =  new ColumnElementType[3];
int index = 0;
columns.AddColumn(Constants.EmailColumnName, email, index++);
columns.AddColumn(Constants.FirstNameColumnName, firstName, index++);
columns.AddColumn(Constants.LastNameColumnName, lastName, index++);

//...

public static void AddColumn(..., int index)
{
  // Add a new column to the column list
  columnListToAddTo[index] = new ColumnElementType { ... };
}

Upvotes: 2

juergen d
juergen d

Reputation: 204924

columnListToAddTo[columnListToAddTo.Length - 1]

because index is starting with 0

Upvotes: 1

Eric Yin
Eric Yin

Reputation: 8973

Use List<ColumnElementType> instead of ColumnElementType[]

Upvotes: 4

Related Questions