How to initialize double dimensional array with zero in c#

19,938

Solution 1

You don't need to do anything.

From Arrays (C# Programming Guide)

The default values of numeric array elements are set to zero, and reference elements are set to null.

So, when you write;

int[,] amn = new int[M,N];

all elements initalized to 0.

You can see on debugger;

enter image description here

Solution 2

As far as I remember Arrays elements are initialized with 0 or null for reference types, so If you make new Array of int's it should have only zeros.

Read this to know more about Arrays

The default values of numeric array elements are set to zero, and reference elements are set to null.

Solution 3

Integer arrays are initialized to 0 by default. So the following code would be functionally equal:

int n = elements;
int m = n * 2;
int[,] amn = new int[m, n];

Or in short:

var amn = new int[elements * 2, elements];
Share:
19,938

Related videos on Youtube

Deepak
Author by

Deepak

Updated on October 14, 2022

Comments

  • Deepak
    Deepak over 1 year

    I'm new to c#. I have two dimensional array. I want to initialize with 0.

    Here is code. I have an error at Array.fill()

    int N = elements;
    int M N * 2;
    int[,] amn = new int[M,N];
    for(int i = 0; i < M; i++)
        Arrays.fill(amn[i], 0);