Array reallocation question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Oleg Subachev

    #1

    Array reallocation question

    Are existing elements in the array preserved when array is reallocated ?

    int[] A = new int[1];
    A[0] = 1;
    A = new int[ A.Length + 1 ];
    A[1] = 2;

    Will A[0] be 1 at this point ?

    Oleg Subachev


  • Marc Gravell

    #2
    Re: Array reallocation question

    No, they aren't. the new array is wiped to 0s. You could, however, create
    the new array in a second variable, then oldArray.CopyTo (newArray, 0) to get
    the values from the old array to the new array.

    However, if you are going to be doing this often, then maybe you are using
    the wrong object structure? Maybe use a list or collection wrapper?

    Marc


    Comment

    • Noah Sham

      #3
      Re: Array reallocation question

      What happens when you run the code in the debugger?

      "Oleg Subachev" <oleg@urvb.ruwr ote in message
      news:%2382SEkH6 GHA.4064@TK2MSF TNGP03.phx.gbl. ..
      Are existing elements in the array preserved when array is reallocated ?
      >
      int[] A = new int[1];
      A[0] = 1;
      A = new int[ A.Length + 1 ];
      A[1] = 2;
      >
      Will A[0] be 1 at this point ?
      >
      Oleg Subachev
      >
      >

      Comment

      Working...