Ric
Ric

Reputation: 693

2-dimensional arrays in C# and how to return the array

I'm having trouble with declaring 2-dimensional arrays in C#, populating them and then returning the array.

At the moment, I'm declaring the array like so:

private static string[,] _programData = new String[50,50];
    public string[,] ProgramData 
    { 
        get 
        { 
            return _programData; 
        } 
    }

_programData is showing the error 'cannot implicitly convert from type 'string[,] to string[][]'

I should point out that I am attempting to call ProgramData from another class like so:

for (serviceCount = 0; serviceCount <= ffm.Program.Length; serviceCount++)
            {
                Console.WriteLine("Program Number: " + ffm.Program[serviceCount].ToString());
                for (serviceDataCount = 0; serviceDataCount <= ffm.ProgramData.Length; serviceDataCount++)
                {
                    **Console.WriteLine("\t" + ffm.ProgramData[serviceCount, serviceDataCount].ToString());**
                }
            }

Error occurs on the bold line above with:

Object reference not set to an instance of an object.

I don't think there seems to be an issue with how I've declared the array, its just the type mismatch that I don't understand.

Regards

Upvotes: 2

Views: 9233

Answers (2)

Breakthrough
Breakthrough

Reputation: 2534

Firstly, calling ffm.ProgramData.Length will return 2500 (50 * 50) as stated above, so you need to fix that count to ffmProgramData.GetLength(1) to return the size of the second dimension.

Secondly, the error you get "Object reference not set to an instance of an object" occurs because you're referencing an uninitialized part of the array. Ensure that the array is filled, or at the very minimum, full of empty strings (obviously you need to run this loop in the constructor changing the variable names where appropriate, because ProgramData is read only as you have it):

for(int fDim = 0; fDim < ffm.ProgramData.GetLength(0); fDim++)
    for(int sDim = 0; sDim < ffm.ProgramData.GetLength(1); sDim++)
        ffm.ProgramData[fDim, sDim] = "";

Thirdly, you don't need to call the ToString() method inside the loop. You're casting a string to a string.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273169

programData is showing the error 'cannot implicitly convert from type 'string[,*] to string[][]'

No, it does not show any error. The code compiles just fine (with C# 3.5).

Upvotes: 1

Related Questions