Array ใน C# เป็น Reference Type ต้องใช้ new สร้าง Instance ก่อนจึงจะ Assign ค่าได้
1. สร้าง Array แล้ว Assign ทีละ Index
double[] prices = new double[5];
prices[0] = 3245.50;
prices[1] = 1234.50;
prices[2] = 8765.50;
prices[3] = 5784.50;
prices[4] = 6576.50;
2. สร้างและ Initialize พร้อมกัน (Collection Initializer)
// Size ระบุชัดเจน
double[] prices = new double[5] { 3245.50, 1234.50, 8765.50, 5784.50, 6576.50 };
// Size Implicit (แนะนำ)
double[] prices = { 3245.50, 1234.50, 8765.50, 5784.50, 6576.50 };
// หรือ
var prices = new[] { 3245.50, 1234.50, 8765.50, 5784.50, 6576.50 };
3. Multi-dimensional Arrays
// 2D Array (Rectangular) - 3 Rows, 4 Cols
int[,] matrix = new int[3, 4] {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
// Access
int val = matrix[1, 2]; // Row 1, Col 2 = 7
// Jagged Array (Array of Arrays)
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5, 6 };
jagged[2] = new int[] { 7, 8, 9 };
// Init Jagged Inline
int[][] jagged2 = {
new int[] { 1, 2 },
new int[] { 3, 4, 5 },
new int[] { 6, 7, 8, 9 }
};
4. Default Values
| Type | Default Value |
|---|---|
| Numeric (int, double, etc.) | 0 / 0.0 |
| bool | false |
| char | '\0' (Null Char) |
| Reference Types (string, class, array) | null |
| Struct | All Fields Zero/Null |
5. Array Initialization Patterns (Modern C#)
// C# 12: Collection Expressions
int[] numbers = [1, 2, 3, 4, 5];
string[] names = ["Alice", "Bob", "Charlie"];
// Span/Stackalloc (Performance)
Span stackArray = stackalloc int[5] { 1, 2, 3, 4, 5 };
ตัวอย่างครบถ้วน
using System;
class Program {
static void Main() {
// 1. Declare + Init
int[] scores = new int[3] { 99, 92, 95 };
// 2. Display
for (int i = 0; i < scores.Length; i++) {
Console.WriteLine($"Score[{i}] = {scores[i]}");
}
// 3. Foreach (Read-only)
foreach (int score in scores) {
Console.WriteLine(score);
}
// 4. Modify
scores[1] = 100;
Console.ReadKey();
}
}
Best Practices
- ใช้
var+ Collection Expression (new[] { ... }หรือ[...]) — Type Inference - หลีกเลี่ยง
new Type[Size] { ... }ที่ Size ไม่ตรงกับ Element Count — Compile Error - Multi-dim: ใช้
[ , ]สำหรับ Rectangular (Matrix),[][]สำหรับ Jagged (Ragged) - Large Arrays: พิจารना
ArrayPool<T>เพื่อ Reuse Memory