Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Từ khóa dành riêng (reserved keywords) trong C#

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
abstractasbaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinin (generic)int
interfaceinternalislocklongnamespacenew
nullobjectoperatoroutout (generic)overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedshortsizeofstackallocstaticstringstruct
switchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatilewhile

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