การประกาศอาร์เรย์ไม่ได้เริ่มต้นอาร์เรย์ในหน่วยความจำ เมื่อเริ่มต้นตัวแปรอาร์เรย์ คุณสามารถกำหนดค่าให้กับอาร์เรย์ได้
ต่อไปนี้เป็นการประกาศและจะไม่สร้างอาร์เรย์ -
int[] id;
ต่อไปนี้สร้างอาร์เรย์ของจำนวนเต็ม อาร์เรย์เป็นประเภทอ้างอิง ดังนั้นคุณต้องใช้คำหลักใหม่เพื่อสร้างอินสแตนซ์ของอาร์เรย์ -
Int[] id = new int[5] {}; เรามาดูตัวอย่างกัน −
ตัวอย่าง
using System;
namespace ArrayApplication {
public class MyArray {
public static void Main(string[] args) {
int [] n = new int[5];
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 5; i++ ) {
n[ i ] = i + 10;
}
/* output each array element's value */
for (j = 0; j < 5; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
}
}
} ผลลัพธ์
Element[0] = 10 Element[1] = 11 Element[2] = 12 Element[3] = 13 Element[4] = 14