Array sizing

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?TmVpbCBC?=

    Array sizing

    In C++ arrays have the .SetAtGrow() method that expands the array to
    accommodate the index specified. I don't find an equivalent method in C#.

    Is there one??

    If not, what is the recommended way to handle this??
    Currently I'm using the Resize(....) method but this can be awkward at times.

    Thanks, Neil
  • Ignacio Machin ( .NET/ C# MVP )

    #2
    Re: Array sizing

    On Mar 28, 4:06 pm, Neil B <Ne...@discussi ons.microsoft.c omwrote:
    In C++ arrays have the .SetAtGrow() method that expands the array to
    accommodate the index specified. I don't find an equivalent method in C#.
    >
    Is there one??
    No
    If not, what is the recommended way to handle this??
    Currently I'm using the Resize(....) method but this can be awkward at times.
    >
    Thanks, Neil
    Use a List<Tcollectio n.

    Comment

    • Jeroen Mostert

      #3
      Re: Array sizing

      Jeroen Mostert wrote:
      public static void SetAtGrow<T>(th is List<Tlist, int index, T item) {
      if (list.Count index) return;
      if (list.Capacity < index) list.Capacity = index;
      list.AddRange(F orever(default( T)).Take(index - list.Count));
      list.Add(item);
      }
      >
      Heh. That's what you get for modifying your code halfway through. The
      obvious fix:

      public static void SetAtGrow<T>(th is List<Tlist, int index, T newElement) {
      if (index < list.Count) {
      list[index] = newElement;
      return;
      }
      if (list.Capacity < index) list.Capacity = index;
      list.AddRange(F orever(default( T)).Take(index - list.Count));
      list.Add(newEle ment);
      }

      --
      J.

      Comment

      • Jeroen Mostert

        #4
        Re: Array sizing

        Jeroen Mostert wrote:
        Jeroen Mostert wrote:
        > public static void SetAtGrow<T>(th is List<Tlist, int index, T item) {
        > if (list.Count index) return;
        > if (list.Capacity < index) list.Capacity = index;
        > list.AddRange(F orever(default( T)).Take(index - list.Count));
        > list.Add(item);
        > }
        >>
        Heh. That's what you get for modifying your code halfway through. The
        obvious fix:
        >
        public static void SetAtGrow<T>(th is List<Tlist, int index, T
        newElement) {
        if (index < list.Count) {
        list[index] = newElement;
        return;
        }
        if (list.Capacity < index) list.Capacity = index;
        list.AddRange(F orever(default( T)).Take(index - list.Count));
        list.Add(newEle ment);
        }
        >
        *sigh* The above code still contains one more bug, but this one is left as
        an exercise to the reader, as I obviously need some refreshments.

        --
        J.

        Comment

        Working...