Like any other variables, arrays must be initialized before we can access and use an element of that array. In C#, initialization of arrays is done automatically with default initial values. For numeral types, the default initialization value is 0, false for bool type, null for reference types, etc.
In addition to the default initialization which happens when we declare our array, we can also initialize it explicitly. There are multiple ways through which we can perform the initialization of arrays. The most simple one is by combining the declaration and initialization in a single statement, using the object initializer syntax:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int[] myArray = { 1, 2, 3, 4, 5, 6 };
Console.ReadLine();
}
}
}
|
But in our previous lesson I said that initialization of arrays can be done this way:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int[] myArray = new int[6];
Console.ReadLine();
}
}
}
|
So, why the difference? True, both statements produce an array of 6 elements of type integer. However, in the first example, we also assign specific values to our array elements, while in the second example, the array is populated with 6 integers, all having the default value of 0. Of course, we can combine the two examples, though this would be an unnecessary complication (since we can simply use our first example):
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int[] myArray = new int[6] { 1, 2, 3, 4, 5, 6 };
Console.ReadLine();
}
}
}
|
The concepts explained in this lesson are also shown visually as part of the following video: