Search code examples
c#arraysallocation

Initializing size of 2D array in runtime using C#


I need to create a 2D array where size of column is fixed as 6 but size of row may vary . How to give dynamic row size in 2D array ? Below is the code I tried but no luck.

int n;
string num = console.ReadLine();
Int32.TryParse(num,out n);
int[,] ar = new int[n,6] ;

Solution

  • There's nothing wrong with the way you're constructing the mulitidimentional array. The following code is valid so I suspect your error is somewhere else:

    int n = 9;
    int[,] ar = new int[n,6];
    

    I'm guessing your input is not coming through correctly so add some error checks to figure out what went wrong. First, Console.ReadLine() has to be capitalized or it wont compile. Next, make sure TryParse is actually functioning properly (it returns a bool indicating success or failure:

    int n;
    string num = Console.ReadLine();
    if (num == null) {
        // ERROR, No lines available to read.
    }
    if (!Int32.TryParse(num,out n)) {
        // ERROR, Could not parse num.
    }
    int[,] ar = new int[n,6];
    

    If issues persist, people generally appreciate more descriptive explanations than "I tried but no luck." Make sure to inform people viewing your question that it was a compilation error or a runtime error and be as specific as you can.