Keywords (từ khóa) là từ dành riêng cho trình biên dịch C#. Không thể dùng làm tên biến, lớp, phương thức... (identifier). Muốn dùng, phải thêm prefix @ (ví dụ: @class, @int).
Một số từ khóa ngữ cảnh (contextual keywords) như get, set, value, async, await... có ý nghĩa đặc biệt trong ngữ cảnh cụ thể nhưng vẫn dùng làm identifier bình thường được.
Bảng từ khóa dành riêng chính:
| Reserved Keywords | ||||||
|---|---|---|---|---|---|---|
| abstract | as | base | bool | break | byte | case |
| catch | char | checked | class | const | continue | decimal |
| default | delegate | do | double | else | enum | event |
| explicit | extern | false | finally | fixed | float | for |
| foreach | goto | if | implicit | in | in (generic) | int |
| interface | internal | is | lock | long | namespace | new |
| null | object | operator | out | out (generic) | override | params |
| private | protected | public | readonly | ref | return | sbyte |
| sealed | short | sizeof | stackalloc | static | string | struct |
| switch | this | throw | true | try | typeof | uint |
| ulong | unchecked | unsafe | ushort | using | virtual | void |
| volatile | while | |||||
Ví dụ dùng từ khóa bool
using System;
using System.Collections;
class Demo
{
static void Main()
{
bool[] arr = new bool[5];
arr[0] = true;
arr[1] = true;
arr[2] = false;
arr[3] = false;
BitArray bArr = new BitArray(arr);
foreach (bool b in bArr)
Console.WriteLine(b);
bool str = arr[1];
Console.WriteLine("Value of 2nd element: " + str);
}
}
Kết quả
True
True
False
False
False
Value of 2nd element: True