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

คีย์เวิร์ด (Keywords) ใน C#

คีย์เวิร์ด (Keywords) ใน C#

คีย์เวิร์ดคือคำสงวนที่คอมไพเลอร์ C# กำหนดไว้ล่วงหน้า ไม่สามารถใช้เป็นตัวระบุชื่อ (identifier) เช่น ชื่อตัวแปร ชื่อคลาส ได้ เว้นแต่จะต่อหน้าด้วยอักขระ @ (เช่น @class)

ประเภทของคีย์เวิร์ด

1. Reserved Keywords (คีย์เวิร์ดสงวน)

คีย์เวิร์ดที่สงวนไว้ใช้งานเฉพาะในภาษา ไม่สามารถใช้เป็น identifier ได้เด็ดขาด

Reserved Keywords
abstractasbaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinin (generic modifier)int
interfaceinternalislocklongnamespacenew
nullobjectoperatoroutout (generic modifier)overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedshortsizeofstackallocstaticstringstruct
switchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatilewhile

2. Contextual Keywords (คีย์เวิร์ดเชิงบริบท)

คีย์เวิร์ดที่มีความหมายเฉพาะในบริบทบางอย่าง สามารถใช้เป็น identifier ได้ในบริบทอื่น

Contextual Keywords
addaliasascendingdescendingdynamicfromget
globalgroupintojoinletorderbypartial (type)
partial (method)removeselectsetvaluevarwhen
whereyield

การใช้ @ กับคีย์เวิร์ด

// ถ้าต้องการใช้คีย์เวิร์ดเป็นชื่อตัวแปร
int @class = 10;        // OK
string @namespace = ""; // OK
var @var = 100;         // OK (แต่ไม่แนะนำ)

คีย์เวิร์ดสำคัญที่ควรจดจำ

  • Modifiers: public, private, protected, internal, static, readonly, const, sealed, abstract, virtual, override
  • Control Flow: if, else, switch, for, foreach, while, do, break, continue, return, goto
  • Exception: try, catch, finally, throw
  • Types: class, struct, interface, enum, delegate
  • Generics: where, in, out
  • Async: async, await
  • LINQ: from, where, select, group, orderby, join, let, into

หมายเหตุ: C# เป็นภาษาที่ case-sensitive ดังนั้น class และ Class จึงต่างกัน (แต่ไม่ควรใช้ชื่อที่ต่างกันแค่ตัวพิมพ์เล็ก/ใหญ่)