ใน C# การ ประกาศ (Declare) อาร์เรย์และ สร้าง (Instantiate) อาร์เรย์ เป็นขั้นตอนแยกกัน
Declaration vs Instantiation
// Declaration เท่านั้น - ยังไม่สร้าง Array ใน Memory
int[] numbers; // null reference
// Instantiation - สร้าง Array จริงบน Heap
int[] numbers = new int[5]; // สร้าง Array ขนาด 5 ค่า Default = 0
// Declaration + Instantiation + Initialization
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
int[] numbers = new[] { 1, 2, 3, 4, 5 }; // Type Inference
int[] numbers = { 1, 2, 3, 4, 5 }; // Shorthand (เฉพาะ Declaration + Init บรรทัดเดียวกัน)
ตัวอย่างครบถ้วน
using System;
namespace ArrayApplication
{
public class MyArray
{
public static void Main(string[] args)
{
// 1. Declare + Instantiate
int[] n = new int[5];
// 2. Initialize Elements
for (int i = 0; i < 5; i++)
{
n[i] = i + 10;
}
// 3. Access Elements
for (int j = 0; j < 5; j++)
{
Console.WriteLine($"Element[{j}] = {n[j]}");
}
}
}
}
ผลลัพธ์
Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14
Default Values หลัง new
| 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 = Default |
Multi-dimensional Arrays
// 2D Rectangular Array
int[,] matrix = new int[3, 4]; // 3 rows, 4 cols
matrix[0, 0] = 1;
// Jagged Array (Array of Arrays)
int[][] jagged = new int[3][];
jagged[0] = new int[2] { 1, 2 };
jagged[1] = new int[3] { 3, 4, 5 };
jagged[2] = new int[1] { 6 };
Array Properties & Methods
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(arr.Length); // 5
Console.WriteLine(arr.Rank); // 1 (Dimension)
Console.WriteLine(arr.GetLength(0)); // 5
// Static Methods
Array.Sort(arr);
Array.Reverse(arr);
Array.Clear(arr, 0, 2); // Set 0,1 to default
int index = Array.IndexOf(arr, 3); // 2
bool exists = Array.Exists(arr, x => x > 3); // True
Common Mistakes
| Code | ปัญหา | แก้ไข |
|---|---|---|
int[] a; a[0] = 1; | NullReferenceException | ต้อง `new int[size]` ก่อน |
int[] a = new int[]; | Compile Error | ต้องระบุ Size หรือ Initializer |
var a = new int[5] {1,2,3,4,5,6}; | Compile Error | Size ต้องตรงกับ Initializer |
Span / Memory (Modern Alternative)
// Stack-allocated Array (No Heap Allocation)
Span stackArray = stackalloc int[5];
for (int i = 0; i < 5; i++) stackArray[i] = i * 10;
// Memory - Heap แต่ Managed
Memory memory = new int[5];
ใน C# การ Initialization (การกำหนดค่าเริ่มต้น) และ Instantiation (การสร้าง Instance) มีความหมายต่างกัน
Initialization (การกำหนดค่าเริ่มต้น)
กำหนดค่าให้ Variable ตอนประกาศ
// Primitive Types
int val = 50; // Initialize ตอน Declar
bool flag = true;
double rate = 3.14;
// Reference Types
string name = "John"; // Initialize กับ String Literal
List list = new List { 1, 2, 3 }; // Initialize ด้วย Collection Initializer
// Array
int[] arr = new int[5] { 1, 2, 3, 4, 5 }; // Initialize Elements
Instantiation (การสร้าง Instance)
สร้าง Object ใหม่จาก Class ด้วย `new` Keyword
// Class Instantiation
Student s1 = new Student(); // 1. Allocate Memory 2. Call Constructor
Student s2 = new Student(); // Instance แยกต่างหาก
// Struct Instantiation (Value Type - No Heap Allocation)
Point p1 = new Point(10, 20); // Calls Constructor
Point p2 = new Point(); // Default Constructor (Zero-init)
Point p3; // Valid for Struct - Zero-initialized automatically
ความแตกต่างสำคัญ
| ด้าน | Initialization | Instantiation |
|---|---|---|
| ความหมาย | กำหนดค่าเริ่มต้นให้ Variable | สร้าง Object Instance ใหม่ |
| ใช้กับ | ทุก Type (Primitive, Struct, Class) | Reference Types (Class, Interface, Delegate, Array) |
| Keyword | ไม่จำเป็น (แต่ใช้ `new` สำหรับ Array/Collection) | ต้องใช้ `new` (หรือ Factory Method) |
| Memory | Stack (Primitive/Struct) หรือ Heap Reference | Heap Allocation (Reference Types) |
| Constructor | อาจเรียก หรืออาจไม่ (Primitive) | เรียก Constructor เสมอ |
ตัวอย่างรวม
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student() { } // Parameterless Constructor
public Student(string name, int age) { Name = name; Age = age; }
}
public class Program
{
public static void Main()
{
// 1. Primitive Initialization (No Instantiation)
int score = 100;
// 2. Struct Initialization (Value Type)
var point = new Point(3, 4); // Instantiation แต่เป็น Value Type (Stack)
// 3. Class Instantiation + Initialization
Student s1 = new Student(); // Instantiation
s1.Name = "Alice"; // Initialization (Property)
s1.Age = 20;
// 4. Combined: Instantiation + Object Initializer
Student s2 = new Student { Name = "Bob", Age = 22 };
// 5. Constructor Parameters
Student s3 = new Student("Charlie", 25);
// 6. Array Instantiation + Initialization
int[] scores = new int[3] { 80, 90, 100 };
Student[] students = new Student[] { s1, s2, s3 };
}
}
Struct vs Class Instantiation
| ด้าน | Class (Reference Type) | Struct (Value Type) |
|---|---|---|
| `new Class()` | Heap Allocation + Constructor | Stack Allocation + Constructor |
| Default Value | null | Zero-initialized (All Fields = 0/null) |
| Assignment | Copy Reference | Copy Value (Entire Struct) |
| Nullability | Can be null | Cannot be null (Unless Nullable<T>) |
Factory Methods (Alternative to new)
public class Connection
{
private Connection() { } // Private Constructor
public static Connection Create(string connectionString)
{
var conn = new Connection();
// Setup...
return conn;
}
}
// ใช้ Factory แทน new
var conn = Connection.Create("Server=...");
สรุป
- Initialization = ให้ค่าเริ่มต้น (Variable/Field/Property)
- Instantiation = `new Type()` สร้าง Object Instance ใหม่บน Heap
- Struct ใช้ `new` ได้แต่เป็น Stack Allocation
- Primitive Types (int, bool, etc.) ไม่มี Instantiation - แค่ Initialization