About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Wednesday, November 07, 2007

Bug?? Reference variable arrays

A co-worker came to me with this problem:




    1         public static int[] MainArray = new int[2] { 0, 0 };


    2         static void Main(string[] args)


    3         {


    4             GetArray();


    5         }


    6         private static void GetArray()


    7         {


    8             MakeNewArray(MainArray);


    9         }


   10         private static void MakeNewArray(int[] p)


   11         {


   12             p[0] = 1;


   13             Console.WriteLine("p[0]:" + p[0].ToString());


   14             Console.WriteLine("MainArray[0]:" + MainArray[0].ToString());


   15             Console.ReadLine();


   16         }






Result:
p[0]:1
MainArray[0]:1

He wanted a copy version of the integer array, but instead it was acting like it was being reference. The response of the code seems wrong since you would expect it to make a seperate array and not reference the MainArray.

What seems to be happening is that since these are arrays, and of the type Reference. Then the arrays are placed on the heap, with the variable names placed on the stack (some what). So, when making a call to a seperate method, the new variable p is then placed on the stack, but pointing to MainArray's values on the heap. Giving a reference type behavior. The solution is to make a copy of the array.




    1         public static int[] MainArray = new int[2] { 0, 0 };


    2         static void Main(string[] args)


    3         {


    4             GetArray();


    5         }


    6         private static void GetArray()


    7         {


    8             MakeNewArray();


    9         }


   10         private static void MakeNewArray()


   11         {


   12             int[] p = new int[MainArray.Length];


   13             Array.Copy(MainArray, p, MainArray.Length);


   14             p[0] = 1;


   15             Console.WriteLine("p[0]:" + p[0].ToString());


   16             Console.WriteLine("MainArray[0]:" + MainArray[0].ToString());


   17             Console.ReadLine();


   18         }







Result:
p[0]:1
MainArray[0]:0

No comments: