Home » C# » C# Keywords (Reserved and Contextual)

C# Keywords (Reserved and Contextual)



C# Keywords are predefined, reserved words that cannot be used as identifiers in the program because these keywords have a special meaning to the compiler. All these keywords are in lowercase and Visual Studio highlights C# keywords in blue color to identify them easily.

Reserved words can be used as identifiers if @ symbol is added as a prefix.
For example, int @if;
This will create a variable @if for type int.

Broadly, keywords are categorized into two types – Reserved and Contextual keywords

  • C# Reserved Keywords– reserved identifiers in any part of a C# program
    • C# reserved keywords cannot be used as an identifier.
    • Using Keyword as an identifier will result in a compile-time error.
  • C# Contextual keywords – considered as keywords in specific contexts.
    • Generally, new keywords are added as contextual keywords in order to avoid breaking c# programs written in older versions.
    • Contextual keywords can be used as an identifier in a limited program context, which can be outside of the context.

Reserved Keywords in C#

The following table lists the available reserved keywords in any part of a C# program. There are 77 predefined reserved keywords.

abstractasbaseboolbreak
bytecasecatchcharchecked
classconstcontinuedecimaldefault
delegatedodoubleelseenum
eventexplicitexternfalsefinally
fixedfloatforforeachgoto
ifimplicitinintinterface
internalislocklongnamespace
newnullobjectoperatorout
overrideparamsprivateprotectedpublic
readonlyrefreturnsbytesealed
shortsizeofstackallocstaticstring
structswitchthisthrowtrue
trytypeofuintulongunchecked
unsafeushortusingvirtualvoid
volatilewhile

Contextual keywords in C#

The keywords in the table are contextual keywords in C# and there are 41 contextual keywords.

addandaliasascendingargs
asyncawaitbydescendingdynamic
equalsfromgetglobalgroup
initintojoinletmanaged
nameofnintnotnotnullnuint
onororderbypartialrecord
removerequiredselectsetunmanaged
valuevarwhenwherewith
yield


The above C# keywords are further categorized under various groups, they are:

TypeKeywords
Access Keywordsbase, this
Access Modifier Keywordspublic, private, protected, internal
Contextual Keywordsadd, var, dynamic, global, set, value
Literal Keywordsnull, false, true, value, void
Method Parameter Keywordsparams, ref, out
Modifier Keywordsabstract, async, const, event, extern, new, override, partial, readonly, sealed, static, unsafe, virtual, volatile
Namespace Keywordsusing, :: operator, extern alias
Operator Keywordsas, await, is, new, sizeof, typeof, stackalloc, checked, unchecked
Query Keywordsfrom, where, select, group, into, orderby, join, let, in, on, equals, by, ascending, descending
Statement Keywordsif, else, switch, case, do, for, foreach, in, while, break, continue, default, goto, return, yield, throw, try, catch, finally, checked, unchecked, fixed, lock
Type Keywordsbool, byte, char, class, decimal, double, enum, float, int, long, sbyte, short, string, struct, uint, ulong, ushort


Naming an Identifier

  • An identifier can not be a C# keyword
  • C# identifiers are case-sensitive
  • must begin with a letter, an underscore or @ symbol
IdentifiersRemarks
demoValid
demo1Valid
productNamesValid
@ifValid, Keyword with prefix @
_demo_itemValid
ifInvalid, C# Keyword
demo$Invalid, because it contains $
demo productInvalid, contains whitespace


C# keywords – Example

using System;

namespace KeywordSample
{
   class Demo
	{         
        // static, public, void are keywords 
		public static void Main(string[] args)
        {
			Console.WriteLine("Words highlighted in blue color are keywords.");
			
			// here int is keyword and number is identifier
			int number = 10;

			// here bool is keyword
			// b is identifier and true is a keyword
			bool b = true;

			byte a = 47;

			// access to public members
			Demo2 d2 = new Demo2();
			d2.count = 77;

			// const is a reserved keyword but can be used as identifier by adding the @ symbol as a prefix.

			// invalid - compiler error
			string const = string.Empty;

			// valid - @ symbol is used as prefix
			string @const = string.Empty;

			// for as statement keyword
			for (int i = 1; i < 3; i++)
			{

			}

            Store store = new Store();
            // sets the value 
            store.Item = "candy";
            // gets the value
            @const = store.Item;

			
        }
   }
	
	class Demo2
	{
		//modifiers keywords
		public int count;
	}
	
	// contextual keywords
   class Store
   {

        // Declare field 
        private string item = string.Empty;

        // Declare property 
        public string Item
        {
            // get is contextual keyword
            get
            {
                return Item;
            }

            // set is a contextual keyword
            set
            {
                Item = value;
            }
        }
    }
}

You can visit the official web page to know the function of each keyword.



Leave a Reply

Your email address will not be published. Required fields are marked *