- Home /
How to circumvent this strange boolean array behaviour?
I'm trying to use a boolean array for some initialization and I ran into something I find rather misleading:
bool boolA = false;
bool boolB = boolA;
boolB = true;
Debug.Log(boolB + ", " + boolA); // Prints "True, False"
bool[] arrayBoolA = new bool[] { false };
bool[] arrayBoolB = arrayBoolA;
arrayBoolB[0] = true;
Debug.Log(arrayBoolB[0] + ", " + arrayBoolA[0]); // Prints "True, True"
For some reason in the second test, the boolean array seems to behave as if it was declared by reference, can someone clarify this point?
Answer by Dave-Carlile · Dec 16, 2012 at 12:33 AM
Array variables are reference types. When you execute arrayBoolB = arrayBoolA you're setting arrayBoolB to the same pointer/reference as arrayBoolA. So when you change the contents of either array they'll both have the same values because they're both referencing the same memory.
If you want a completely separate array you should be able to use Array.Copy to copy the contents into a different reference to the same type of array.
Thanks a lot Dave, Array.Copy did the trick. Come to think of it, I guess it makes sense since referencing is the default for "heavy" objects.
Nevertheless, I find it somewhat strange that in my code the array was defined as private set in a class, yet no error/warning was raised when the variable it was assigned to in another class was modified.
Your answer
Follow this Question
Related Questions
question about array or list of boolean 1 Answer
How to Spawn objects at a certain score. 1 Answer
multiple rows, in an array in C# 2 Answers
How can I do a foreach loop for an array of booleans? 1 Answer
Collecting Array items in order 1 Answer