Roshni Gandhi Roshni Gandhi - 24 days ago 6
C# Question

assigning value to 2d array is giving me exception

I am trying to assign values to 0th position in 2D integer array and it is giving me Nullreference exception, though I am passing proper values.
here is the code

public static int[,] Ctable;
private static void GetTable(int m,int n)
{
m = 16;
for (int i = 1; i <= m; i++)
{
Ctable[i, 0] = 1; // Here it is giving Exception
}
}

Answer

You don't initialize the 2D array Ctable correctly, it's still null. See my example below. I initialize the array with the size of the input parameter m and n of the method void GetTable(int m, int n).

Your loop is not correct as well. Arrays are zero indexed (0, n - 1). You will find some additional information to initialize arrays here.

public static int[,] Ctable;

private static void GetTable(int m, int n)
{
    Ctable = new int[m, n]; // Initialize array here.

    for (int i = 0; i < m; i++) // Iterate i < m not i <= m.
    {
        Ctable[i, 0] = 1;
    }
}

However, you will always overwrite Ctable. Probably you're looking for something like:

private const int M = 16; // Size of the array element at 0.

private const int N = 3; // Size of the array element at 1.

public static int[,] Ctable = new int [M, N]; // Initialize array with the size of 16 x 3.

private static void GetTable()
{
    for (int i = 0; i < M; i++)
    {
        Ctable[i, 0] = 1;
    }
}