C
C#2mo ago
MHK

✅ GetLength vs .Length

static void Main(string[] args)
{
int[,,] ints = new int[,,] {

{ {1,2,3},
{4,5,6},
{7,8,9} },
{
{10,10,11},
{11,12,13},
{12,13,14}

}


};
for (int i = 0; i < ints.GetLength(0); i++)
{
for (int j = 0; j < ints.GetLength(1); j++)
{
for(int k = 0; k < ints.GetLength(2); k++)
{
Console.WriteLine(ints[i, j, k]);
}
}
}
Console.ReadLine();
}
static void Main(string[] args)
{
int[,,] ints = new int[,,] {

{ {1,2,3},
{4,5,6},
{7,8,9} },
{
{10,10,11},
{11,12,13},
{12,13,14}

}


};
for (int i = 0; i < ints.GetLength(0); i++)
{
for (int j = 0; j < ints.GetLength(1); j++)
{
for(int k = 0; k < ints.GetLength(2); k++)
{
Console.WriteLine(ints[i, j, k]);
}
}
}
Console.ReadLine();
}
the thing is .GetLength(0) doesn't need a -1 in the end while in .Length we do it like .Length-1
6 Replies
unhAPI
unhAPI2mo ago
wdym, if you did a for with .Length you wouldn't use < Length-1
MHK
MHK2mo ago
oh I feel I we use it? when we count length right? int lngt=sentence.length-1 like this but this is a different scenerio! I will look to clear my confusion sorry I am newbie I sometimes...
unhAPI
unhAPI2mo ago
both GetLength and Length return a "count", or a dimension, so it's the same principle anyway again if you were to have a for on an array using Length it would be used the same as GetLength for (int i = 0; i < ints.GetLength(0); i++) === for (int i = 0; i < array.Length; i++) i don't know if this answers your question
MHK
MHK2mo ago
ty man I had a wrong understanding before previosly when I worked on a words counter userInput.Length gives you the total number of characters in the userInput string. In C#, strings are zero-indexed, meaning the first character is at index 0, and the last character is at index userInput.Length - 1. So I just mixed this everywhere thinking it's needed at all place
unhAPI
unhAPI2mo ago
it happens all the times to mix 1-based index and 0-based index code, you probably have to come with a system to not forget this depending maybe on which you find the most intuitive
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server