Link to home
Start Free TrialLog in
Avatar of Dinesh Bali
Dinesh Bali

asked on

Array Length

Hi,

In C# code I wanted to understand why output of below code is 18

int[,,] x = new int[3,2,3];
            Console.WriteLine(x.Length);

Open in new window


Please advise
ASKER CERTIFIED SOLUTION
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
x.length will return the full size that is 18. In order to get the correct length for each dimension,  you need to use GetLength  method:
int[,,] x = new int[3,2,3];
Console.WriteLine(x.GetLength(0)); // Writes 3
Console.WriteLine(x.GetLength(1)); // Writes 2
Console.WriteLine(x.GetLength(2)); // Writes 3

Open in new window

Avatar of Dinesh Bali
Dinesh Bali

ASKER

Hi David,
Many thanks for your reply.
Why it is multiplying the numbers?

Please explain the reason.
Any link to understand this.


Hi Miguel,

I am preparing for some test.
This is from practice test. I need to choose correct answer.

Since, I don't understand the logic, so I asked here.

Hence I  cannot manipulate the method.

Please help understanding the logic.
Thanks understood that this is multi dimension array.
I guess you've never run into arrays before or are used to only single dimension arrays
int[] x = new int[];

you are getting the total number of elements in the array and not the size of the array in memory.
if you change int to double or float you get the same number