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

Identifiers (ตัวระบุชื่อ) ใน C# คืออะไร

Identifier คือชื่อที่ใช้ระบุ Class, Variable, Method, หรือ User-defined Item อื่นๆ

กฎการตั้งชื่อ (Naming Rules)

  1. ขึ้นต้นด้วย ตัวอักษร (Letter) หรือ Underscore (_) - ไม่ใช่ตัวเลข
  2. ตามด้วย ตัวอักษร, ตัวเลข (0-9), หรือ Underscore (_) ได้
  3. ไม่มี Space หรือ Special Characters: ? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / \
  4. ไม่ใช่ C# Keywords (Reserved Words)
  5. Case-sensitive: myVar ≠ MyVar

ตัวอย่าง Identifiers ที่ถูกต้อง

Class Names (PascalCase)

class Calculation
class Demo
class EmployeeManager

Method Names (PascalCase)

void Display()
void GetMarks()
void CalculateTotalPrice()

Variable/Field Names (camelCase)

int age;
int marks;
double resultMarks;
string _privateField; // Convention: private fields เริ่ม _

Constants (PascalCase หรือ UPPER_SNAKE_CASE)

const double PI = 3.14;
const int MAX_SIZE = 100;

Identifiers ที่ผิด (Invalid)

int 2names;      // เริ่มด้วยตัวเลข ❌
int my-name;     // มี hyphen ❌
int class;       // เป็น Keyword ❌
int my name;     // มี Space ❌

@ Prefix สำหรับ Keywords

สามารถใช้ Keyword เป็น Identifier ได้โดยเติม @ นำหน้า:

int @class = 5;  // ถูกต้อง
string @string = "hello";