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

I am having trouble declaring 2-dimensional arrays in C #, filling them in and then returning the array.

Currently I am declaring an array like this:

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

      

_programData shows error 'cannot implicitly convert from type' string [,] to string [] [] '

I have to point out that I am trying to call ProgramData from another class like this:

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());**
                }
            }

      

The error on the highlighted bold line above:

An object reference is not set on an object instance.

I don't think there is a problem with the way I have declared the array, it is just a type mismatch that I don't understand.

Hello

+2


source to share


2 answers


First, the call to ffm.ProgramData.Length will return 2500 (50 * 50) as above, so you need to correct that count in ffmProgramData.GetLength (1) to return the size of the second dimension.

Second, the error you get, "Object reference not set to an object instance" occurs because you are referencing an uninitialized portion of the array. Make sure the array is full, or at least filled with blank lines (obviously, you need to run this loop in the constructor, changing the variable names when necessary, because ProgramData is only read as you know 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] = "";

      

Third, you don't need to call the ToString () method inside the loop. You are inserting a line into a line.

+2


source


programData shows error 'cannot implicitly convert from type' string [, *] to string [] [] '



No, it doesn't show any errors. The code compiles just fine (since C # 3.5).

+1


source







All Articles