mistergreen
mistergreen

Reputation: 109

GetLength() method does not work as expected on an array

Here is a C# code.

It outputs the following text :

tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 0
Length of dim 1 of tab : 1

I expected the following text :

tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 2
Length of dim 1 of tab : 3

Why not? Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] tab = new int[2, 3];

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    tab[i, j] = 2 * i + j;
                }
            }
            Console.WriteLine("tab.Length = {0}", tab.Length);
            Console.WriteLine("tab.Rank = {0}", tab.Rank);
            for (int i = 0; i < tab.Rank; i++)
            {
                Console.WriteLine("Length of dim {0} of tab : {0} ", i, tab.GetLength(i));
            }

        }
    }
}

Upvotes: 1

Views: 474

Answers (3)

Dylan Meador
Dylan Meador

Reputation: 2401

Do you simply need to access the second parameter passed to the Console.WriteLine? Try this:

Console.WriteLine("Length of dim {0} of tab : {1} ", i, tab.GetLength(i));

Upvotes: 1

Steve B
Steve B

Reputation: 37710

Your format string is wrong.

Replace "Length of dim {0} of tab : {0} " by "Length of dim {0} of tab : {1} ".

Your code was actually putting i, and not tab.GetLenght(i)

Upvotes: 1

millimoose
millimoose

Reputation: 39990

Wild guess: your last format string is wrong:

Console.WriteLine("Length of dim {0} of tab: {0} ", i, tab.GetLength(i));

You're using {0} twice, so you're outputting the value of i in both placeholders.

Use this instead:

Console.WriteLine("Length of dim {0} of tab: {1} ", i, tab.GetLength(i));

Upvotes: 11

Related Questions