I'm a programming newbie and I just started learning about arrays. What confuses me is the way one can initialize a multidimensional array in C#. And that is because I don't specify the coordinates of each element myself, but C# does it somehow.
More specifically, let's say that I initialize this array:
string[,] names = {
{"Deadpool", "Superman", "Spiderman"}
{"Catwoman", "Batman", "Venom"}
};
Given that in single dimensional array initialization C# starts by placing the first value in element [0], I assume that the same holds true for multi-dimensional arrays too. But doesn't it do the same for each seperate dimension ?This can't be true. Because then it would place "Deadpool" on element [0] of the row, and later it would try to place "Catwoman" on element [0] of the first column. And if that was the case, given that element [0] of the first row is the same element [0] of the first column, "Catwoman" would replace "Deadpool" as both would be written in [0,0]. Yet using a foreach
to write everything on the console, both show up. So how and where does C# place each value, to avoid a value of one dimension overwriting the value of another dimension ?
If you convert the foreach to a for loop it might mack a little bit more sense:
static void Main(string[] args)
{
string[,] names = {{"Deadpool", "Superman", "Spiderman"},{"Catwoman", "Batman", "Venom"}};
for (int index0 = 0; index0 < names.GetLength(0); index0++)
{
for (int index1 = 0; index1 < names.GetLength(1); index1++)
{
var name = names[index0, index1];
Console.Write(name);
}
}
}
This is essentially what the foreach is doing behind the scenes. If you want to learn how that actually works start here:
How does the Java 'for each' loop work?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.