locked
allocating arrays RRS feed

  • Question

  • Hello, I am quite new to coding and I just want some clarification.

    What does it mean to declare an integer array variable, but not to allocate the array itself?

    I don't understand what it is supposed to look like

    thank you!

    Sunday, November 4, 2018 1:18 AM

All replies

  • In C#, like many modern languages, your variable is not really the array.  It is a reference -- basically, the address of the array.  So:

        int[] iarray;

    That declares a variable called "iarray" that is able to refer to an array.  At the current time, however, there is no array for it to reference.  It contains an empty reference -- a null reference.  Trying to use the array will cause an exception.  When you say:

        iarray = new int[] { 1, 2, 3, 4, 5 };

    That creates an anonymous array object with 5 elements, and makes the "iarray" variable refer to that array.  If you now say:

        int[] jarray = iarray;

    That doesn't create a new array.  Instead, both of those variables will refer to the same anonymous array object.  If you delete iarray, the array object still exists, with a single reference called "jarray".

    This is an important concept in C#.  Objects are all anonymous, live in a big nameless object cloud.  Your variables will have references to those nameless objects over time, possibly with different names as the program goes on.  This is the reason why we need to have a garbage collector -- it periodically scans the big nameless object cloud looking for objects that don't have any references.  Such objects can be truly deleted.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Proposed as answer by RLWA32 Sunday, November 4, 2018 10:17 AM
    Sunday, November 4, 2018 1:32 AM
  • Thank you so much!!! I understand it!
    Sunday, November 4, 2018 2:43 AM
  • Thank you so much!!! I understand it!

    You should  have marked the post that answered your questions successfully as 'Answered' 
    Sunday, November 4, 2018 9:50 AM