Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่างการประกาศ (Declaration) และการกำหนดค่า (Assignment) ใน C#

Declaration vs Initialization vs Assignment ใน C#

สามขั้นตอนนี้สับสนง่าย แต่มีความหมายเฉพาะเจาะจงใน C#

1. Declaration (การประกาศ)

บอกคอมไพเลอร์ว่ามีตัวแปรชื่อนี้ ชนิดนี้ **จองพื้นที่หน่วยความจำ** แต่ **ยังไม่มีค่า** (ยกเว้น field ของ class ที่มี default value)


// ตัวแปร local - ต้อง initialize ก่อนใช้ (compile error ถ้าไม่)
int x;        // Declaration only - unassigned
// Console.WriteLine(x); // ❌ Error: Use of unassigned local variable

// Field ใน class - มี default value อัตโนมัติ
class MyClass
{
    int field; // Default = 0
    string name; // Default = null
}

2. Initialization (การกำหนดค่าเริ่มต้น)

กำหนดค่า **ครั้งแรก** ให้ตัวแปร สามารถรวมกับ Declaration ได้


// Declaration + Initialization ในบรรทัดเดียว
int x = 10;           // พื้นฐาน
int[] arr = new int[5]; // Array initialization (default 0)
List list = new List(); // Object initialization

// Object initializer
var person = new Person { Name = "John", Age = 30 };

// Collection initializer
var numbers = new List { 1, 2, 3 };
var dict = new Dictionary { ["a"] = 1, ["b"] = 2 };

3. Assignment (การกำหนดค่า/มอบหมาย)

เปลี่ยนค่าของตัวแปรที่ **มีอยู่แล้ว** ใช้ operator =


int x = 10;    // Declaration + Initialization
x = 20;        // Assignment (เปลี่ยนค่า)
x += 5;        // Compound assignment (x = x + 5)

Array: Declaration, Initialization, Assignment


// 1. Declaration only
int[] arr; 

// 2. Initialization (จองหน่วยความจำ)
arr = new int[5]; // ทุก element = 0 (default)

// 3. Assignment (กำหนดค่าแต่ละ element)
arr[0] = 100;
arr[1] = 200;

// รวมทั้ง 3 ขั้นตอนในบรรทัดเดียว
int[] arr2 = new int[5] { 10, 20, 30, 40, 50 };

// Implicitly typed array
var arr3 = new[] { 1, 2, 3 }; // int[]

Default Values ของชนิดข้อมูล

CategoryTypeDefault Value
Value Typesint, long, byte, short0
float, double0.0
decimal0.0m
boolfalse
char'\0' (null char)
structทั้งหมดเป็น default ของแต่ละ field
enum0 (ค่าแรก)
Nullable<T>null
Reference Typesclass, string, array, delegatenull
interfacenull
dynamicnull

Target-typed new (C# 9+)


// ไม่ต้องเขียนชนิดข้อมูลซ้ำ
List list = new(); // แทน new List()
Dictionary dict = new();
int[] arr = new[] { 1, 2, 3 }; // ยังต้องการ [] สำหรับ array

สรุปความแตกต่าง

ขั้นตอนคำอธิบายตัวอย่าง
Declarationประกาศชื่อและชนิด จองหน่วยความจำint x;
Initializationกำหนดค่า **ครั้งแรก**int x = 10; หรือ x = 10; (ครั้งแรก)
Assignmentเปลี่ยนค่า **หลังจาก initialized แล้ว**x = 20;

กฎสำคัญ: ตัวแปร Local ต้อง **Definitely Assigned** ก่อนใช้งาน (Compiler บังคับ)