Khai báo mảng không khởi tạo mảng trong bộ nhớ. Cần new để cấp phát.
int[] id; // Chỉ khai báo reference, null
int[] id = new int[5] {}; // Tạo mảng 5 phần tử, giá trị mặc định 0
Ví dụ
using System;
namespace ArrayApplication
{
public class MyArray
{
public static void Main(string[] args)
{
int[] n = new int[5];
int i, j;
// Khởi tạo phần tử
for (i = 0; i < 5; i++)
{
n[i] = i + 10;
}
// Xuất
for (j = 0; j < 5; j++)
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
}
}
}
Kết quả
Element[0] = 10 Element[1] = 11 Element[2] = 12 Element[3] = 13 Element[4] = 14
Tóm tắt:
int[] a;- reference = nullint[] a = new int[5];- allocate mảng 5 int, giá trị 0int[] a = {1,2,3};- khai báo + khởi tạo (implicit new)- Mảng là reference type, lưu trên heap