views:

1183

answers:

1

Hi,

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

+2  A: 

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.

Breakthrough
This has solved the issue. I get no error messages now but my 2d array doesn't seem to be populated by my data i.e. it is printing out blanksI will try and sort this out but many thanks for now.
Ric Coles