Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

2D arrays, declaration, initialization, memory, getting length

Notes:

C# Two dimensional arrays:
I. Declaring and initializing 2D array: [Starts at: 00min:00sec]
II. Memory representation of 2D array : [Starts at: 02min:03sec]
III. Different ways of initializing 2D array members: [Starts at: 08min:53sec]
IV. Length property Vs. GetLength method: [Starts at: 14min:43sec]

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {

// Declaring and initializing an array variable
int[,] numbers1 = new int[2,2];

// 1.way : initializing array members
int[,] numbers2 = new int[2, 2]{
{1,2},
{1,2},
};

// 2. way: initializing array members
int[,] numbers3 = new int[, ]{
{1,2},
{1,2},
};

// 3. way: initializing array members
int[,] numbers4 = {
{1,2},
{1,2},
};

// setting values
numbers2 [0, 0] = 10;

// getting values
Debug.Log (numbers2 [0, 0]); // 10

Debug.Log (numbers2.Length); // 4 : total elements

Debug.Log (numbers2.GetLength (0)); // 2: total number of rows

Debug.Log (numbers2.GetLength (1)); // 2: total number of cols

}
}

// Note arrays must of same dimention
// To utilize memory in C# we have jagged arrays
// Will talk about them later