Neil said:
In C++ arrays have the .SetAtGrow() method that expands the array to
accommodate the index specified.
You're talking about the MFC CArray class. That's not the same thing as a
"C++ array". C++ has plain old C arrays, but those don't grow.
I don't find an equivalent method in C#.
Is there one??
No. Array objects are immutable in C# (their contents are not, of course).
If not, what is the recommended way to handle this??
Use a List<T> instead. (That's not a linked list, contrary to what you might
think, it's the equivalent of an STL vector.)
List<T> has no way of automatically expanding to a specified index, but it's
easy enough to achieve. Here's an extension method in C# 3 that will achieve
the same as CArray::SetAtGrow:
public static void SetAtGrow<T>(this List<T> list, int index, T item) {
if (list.Count > index) return;
if (list.Capacity < index) list.Capacity = index;
list.AddRange(Forever(default(T)).Take(index - list.Count));
list.Add(item);
}
public static IEnumerable<T> Forever<T>(T item) {
while (true) yield return item;
}
If you're going to do this a lot, you'll want to set .Capacity to a
reasonable value before, to minimize reallocations. If the list you're going
Currently I'm using the Resize(....) method but this can be awkward at times.
I'll say. It'll be especially awkward for performance. .Resize() does not
actually resize an array, it creates a brand new one -- the documentation
explains this.