Im getting into C# and im a little bit confused about an example of the resource im learning from. Its about the declaration and initialisation of a bool array, id like to know what happens at what point in the code:
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
myBools[0][0] = true;
//myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
I declare a 2 dimensional bool array of unknown size - in the same line I initialize the array of array with 2 arrays of booleans.
What do I have at that moment in the array? C# doesnt allow to read out the values. (I think I now have an array_main with 2 members containing uninitialized! bool arrays_members is this correct? So an array of len 2 containing 2 members that are bool arrays of unkown lenght containing NULL?)
In line 2 and 3 I initialize the array_members with boolean arrays, the first member with lenght 2 and the second one with lenght 1. Is this correct?
After that its simple, C like.
I can work with the logic, but id like to know whats going on behind the scenes.
I declare a 2 dimensional bool array of unknown size
Well, you declare an array of arrays. It's not a "real" multi-dimensional array - that would be bool[,] myBools
. It's worth understanding the difference between jagged arrays (an array where the element type is another array type) and rectangular arrays (where there's a single array object, but with multiple dimensions).
What do I have at that moment in the array?
You have two null references. This is easy to see:
bool[][] myBools = new bool[2][];
bool[] array = myBools[0];
Console.WriteLine(array == null); // true
Basically, you're just creating an array where the element type is a reference type. Think of it as if you had a class called BoolArray
, and you created:
BoolArray[] myBools = new BoolArray[2];
Then you'd expect both elements to have a value of null, because that's the default for all reference types, right? Well, that's exactly what you've got... it's just that the array type is bool[]
rather than a simple class.
In line 2 and 3 I initialize the array_members with boolean arrays, the first member with length 2 and the second one with length 1. Is this correct?
Yes, exactly.
See more on this question at Stackoverflow