How to set data to array in compile and run time
Compile time and run time initialization of 2D
array in C#
In this article we will see how to
initialize 2 dimension array in compile time and run time. If you are new in C#
programming I hope you will enjoy this article.
Let’s get some idea of two dimension
array.
Tow dimension array are nothing but
combination of single dimension array. It represents data in table format. Data
store in consecutive memory location . We will see how to define 2 dimension
array in c#.
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. Within square bracket we can
specify size of array like [row,column] . Here we can see size array is 2 X 2
means maximum we can store 4 integer values within this array. When we create
array by default it’s initialize by 0 (If it is integer array). Now we have to
put our own value to work with. There are two different ways to set value
within array, we will see both of them in below example.
Set value
in compile time
This type of initialization is called
compile time initialization because we are setting value when we are writing
code or compiling time. Let’s try to understand below example.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
int [,] MyArray = new int[2,2];
MyArray[0, 0] = 100;
MyArray[0, 1] = 100;
MyArray[1, 0] = 100;
MyArray[1, 1] = 100;
Console.WriteLine("Static initialisation");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write(MyArray[i, j] + " ");
}
Console.WriteLine("\n");
}
Console.ReadLine();
}
}
}

Now, one
big problem of this type of initialization is, User cannot give value in run
time. Means this array is not capable to work with user’s value. In next
example we will see how to solve it.
Set value in Run time
This is standard way of initialization.
User can able to set their value with array and array can able to process it.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Globalization;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
int [,] MyArray = new int[2,2];
Console.WriteLine("Static initialisation");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("Please enter number");
MyArray[i, j] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\n");
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write(MyArray[i, j] + " ");
}
Console.WriteLine("\n");
}
Console.ReadLine();
}
}
}
Conclusion :
This is how we can set value to array in compile and run time