คำตอบสั้น
ไม่สามารถปรับขนาดอาร์เรย์ได้โดยตรง (arrays are fixed-size) แต่ใช้ Array.Resize<T>() สร้างอาร์เรย์ใหม่ขนาดต่างกัน คัดลอกข้อมูล แล้วแทนที่ตัวแปรเดิม
ตัวอย่างการใช้ Array.Resize
using System;
class Program
{
static void Main()
{
char[] ch = new char[10];
ch[0] = 'a'; ch[1] = 'b';
Array.Resize(ref ch, 10); // ขนาดเดิม 10 -> ใหม่ 10 (ตัวอย่าง)
for (int i = 2; i < 10; i++) ch[i] = (char)('c' + i - 2);
Console.WriteLine("New Array: " + new string(ch));
}
}
ผลลัพธ์
New Array: abcdefghij
รายละเอียด Array.Resize
- Signature:
void Resize(ref T[] array, int newSize) - ต้องใช้
refเพราะอาจสร้างอาร์เรย์ใหม่และเปลี่ยน reference - ขนาดใหม่ > เดิม: เติม default(T) (0, null, false)
- ขนาดใหม่ < เดิม: ตัดทิ้งส่วนท้าย
- เป็น O(n) ต้อง allocate ใหม่และคัดลอก
ทางเลือกที่ดีกว่าสำหรับข้อมูลไดนามิก
List<T>- เพิ่ม/ลดขนาดได้ ยืดหยุ่น ใช้งานง่ายQueue<T>,Stack<T>- โครงสร้างข้อมูลเฉพาะทางArrayList- legacy non-generic (ไม่แนะนำ)