C# - How to declare a 2D array in run time

Related searches

I am currently working on a console minesweeper application where a number of mines are generated and each array index needs to display the number of adjacent mines.

The user will need to define the number of rows and columns.

public class Board
    private static int row;
    private static int column;
    private static int fields;

    public static int Row { get => row; set => row = value; }
    public static int Column { get => column; set => column = value; }
    public static int Fields { get => fields ; set => fields = value; }

    Random random = new Random();
    public int randomX;
    public int randomY;

    public string[,] boardArr = new string[Row, Column];

    public void EnterBoardDimensions()
        Console.Write("Enter number of rows: ");
        Row = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter number of columns: ");
        Column = Convert.ToInt32(Console.ReadLine());


        Console.Write("Enter number of fields: ");
        Fields = Convert.ToInt32(Console.ReadLine());

    public void DrawBoard()
        for(int fields = 0; fields < Fields; fields++)
            Console.WriteLine("\n\nField #{0}", fields + 1);
            Console.Write("\n" + row + " x " + column);
            for (int r = 0; r < Row; r++)
                for (int c = 0; c < Column; c++)
                    boardArr[r, c] = ".";

                    //randomX = random.Next(0, Row - 1);
                    //randomY = random.Next(0, Column - 1);

                    boardArr[randomX, randomY] = "*";

                    Console.Write(boardArr[r, c]);

At design time you declare the type and the name of the array. The array object having a specific size is always created at runtime.

// Design time
Mine[,] _mineField;

// Run time
_mineField = new Mine[m, n];

Here I assume that you have declared a Mine class, struct or enum. Of course it could be any other type (int[,], char[,] etc.).

Also, the generic List<T> has replaced the old ArrayList in most cases. Lists have the advantage that they can grow dynamically. But this is not a requirement here. Once you have created the array object, its size must not change. If you need another size in the next round, just create a new array.

Note that the array indexes are zero-bound. i.e. it will have the ranges

_mineField[0 .. m - 1, 0 .. n - 1]

Multidimensional Arrays, Arrays in C# can have more than one dimension. This example declaration creates a two-dimensional array of four rows and two columns. Define 2 dimension array. It’s pretty simple to define 2 dimension array. Just follow below line. int [,] MyArray = new int [2,2]; Here we can see data type of array is integer and name of array is MyArray which contents base address of array which has created in memory.

You most certainly can create a two-dimensional array with dynamic values taken from user input. E.g.:

Console.WriteLine("Please enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of columns: ");
int cols = Convert.ToInt32(Console.ReadLine());

int[,] board = new int[rows, cols];

C# - Multidimensional Arrays, C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as − string [ � Input array size at run time and declare an array . Here, we will input array length and will declare an array of variable length (according to input value). Syntax: int[] arr = new int[len]; Here, len is a variable, that will be read from the user. 2) C# example to Input length and declare an array at run time, input and print array elements

Resolved. I didn't notice that I was declaring the bounds of the array outside of the code, and therefore row and column variables were defaulting to 0.

C# 2D Array Examples, In this 2D world, an element is addressed with X and Y. Consider now C#. Part A: Here we initialize the 2D array with an initializer expression. Runtime. CompilerServices; class Program { const int _max = 10000000; static void Main() { int[� To get some more practice with arrays, add another button to your form. Set the text to be this: Exercise: Times Table. Now double click the button and add the following code: When you run your programme and click the button, your form should look something like ours: Notice that the 5 times table is displayed in the list box.

2d Array in C# with real-time Examples, Common Language Runtime in .NET .NET Program Execution Process Assigning values to two-dimensional array in C# at the time of declaration: namespace� Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns. C#. int[,] array = new int[4, 2]; The following declaration creates an array of three dimensions, 4, 2, and 3. C#.

Create a two-dimensional array at runtime, C#[edit]. class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console. DARI S D DIM(10) INZ(D'09/15/1994') * * Compile-time arrays in alternating format. Both arrays have * eight elements (three elements per record). ARC is a character * array of length 15, and ARD is a time array with a predefined * length of 8.

Declaring Arrays. To declare an array in C#, you can use the following syntax −. datatype [] arrayName; where, datatype is used to specify the type of elements in the array. [ ] specifies the rank of the array. The rank specifies the size of the array. arrayName specifies the name of the array.

  • "however this cannot be achieved using 2D arrays" Why not?
  • What do you mean "declare a 2d array at runtime?" Declare the array bounds?
  • Exactly. for instance setting an array of 5 rows and 3 columns.
  • "I have researched and came to the conclusion of using ArrayList of List." - That's not a question. What exactly are you asking? If you have code which isn't doing what you expect, show the code and explain the problem.
  • Note that random.Next(Row) always returns a number in the range [0 .. Row - 1]. You also mix up clearing the board and defining mines. The fields loop should be separated from the row and column loops and be executed after all the elements have been initialized to ".".
  • I've tried that and I keep getting an 'Index was outside the bounds of the array'
  • @iMattu please share the code the produces that error. This snippet alone cannot.