Software & Finance





C# - Dynamic Arrays





Allocating dynamic arrays are easier in C#. Allocating an array like [3 X 4 X 5] is easier as we can use loop. Look at the int values allocation in the sample code given below.

 

      int [,,] values = new int[3,4,5];

 

In C#, the above syntax is called multi dimensional arrays.

 

However if you need a variable length on each dimension, you need to explicitly mention on each level. For example,

 

      long [][][] buffer = new long [2][][];

 

buffer[0] and buffer[1] can have independent size. I have given here the sample code for allocating 3 dimensional array of long.

 

In C#, the above syntax is called jagged arrays or array of arrays.

 

 

Source Code


namespace Basics

{

class Sample

{

 

static void Main(string[] args)

{

      int [,,] values = new int[3,4,5];

 

            string[] samplNames1 = new string[4] { "Kathir", "Lachu" , "Software", "Finance" };

            string[,] samplNames = new string[2, 2] { { "Kathir", "Lachu" }, { "Software", "Finance" } };

 

 

            int [,,] values = new int[3,4,5];

 

            // 3 Dimensional Arrays

            long [][][] buffer = new long [2][][];

            buffer[0] = new long [3][];

            buffer[1] = new long [4][];

 

            // buffer[0][Y][Z] is initialized along with memory allocation

            buffer[0][0] = new long[2] { 100, 200 };

            buffer[0][1] = new long[3] { 200, 400, 500 };

            buffer[0][2] = new long[4] { 600, 700, 800, 900 };

 

            buffer[1][0] = new long[2];

            buffer[1][1] = new long[2];

            buffer[1][2] = new long[2];

            buffer[1][3] = new long[3];

           

            buffer[1][0][0] = 100;

            buffer[1][0][1] = 200;

 

            buffer[1][1][0] = 300;

            buffer[1][1][1] = 400;

 

            buffer[1][2][0] = 500;

            buffer[1][2][1] = 600;

 

            buffer[1][3][0] = 700;

            buffer[1][3][1] = 800;

            buffer[1][3][2] = 900;

}

 

}

}

 

 

Output


I have used Visual Studio Debugger - Quick Watch for more clarity in the output