C# Keywords (Reserved, Contextual)

In c#, Keywords are the predefined set of reserved words that have special meaning for the compiler. So the keywords in c# cannot be used as an identifiers such as variable name, class name, etc. in our applications.

C# Use Keywords as Variable Names

In case, if you want to use a Keywords as variable names (identifiers), then you need to include @ as a prefix for your variable names. For example, @switch is a valid identifier but switch is not because it’s a keyword and having a special meaning for the compiler.

 

Following is the example of using the reserve keywords as a variable names by including @ as a prefix in c# programming language.

 

using System;

 

namespace CsharpExamples

{

    public class @class

    {

        public int age;

    }

    class Program

    {

        static void Main(string[] args)

        {

            @class p1 = new @class();

            p1.age = 10;

            Console.WriteLine("Age: "+p1.age);

            Console.WriteLine("Press Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above c# example, we used a class keyword as a variable name (@class) by including @ as a prefix.

 

When we execute above program we will get the result like as shown below.

 

C# Use Reserve Keywords as a Variable Names Example Result

 

This is how we can use keywords as a variable names in c# programming language based on our requirements.

Different types of Keywords in C#

In c#, Keywords are differentiated as a two types, those are

 

  • Reserve Keywords
  • Contextual Keywords

C# Reserved keywords

Following table lists the available reserved keywords in c# programming language.

 

abstract bool continue decimal default
event explicit extern char checked
class const break as base
delegate is lock long num
byte case catch false finally
fixed float for as foreach
goto if implicit in int
interface internal do double else
namespace new null object operator
out override params private protected
public readonly sealed short sizeof
ref return sbyte stackalloc static
string struct void volatile while
true try switch this throw
unchecked unsafe ushort using using static
virtual typeof uint ulong out (generic modifier)

C# Contextual keywords

In c#, Contextual keywords can be used as an identifier in a limited program context and that can be an outside of the context.

 

Generally, whenever the new keywords are added to the C# language, those are treated as a Contextual keywords in order to avoid the breaking of c# programs which we written in older versions.

 

Following table lists the available Contextual Keywords in c# programming language.

 

add alias async await dynamic
from get orderby ascending decending
group into join let nameof
global partial set remove select
value var when Where yield

These are the keywords available in c# programming language and we can use it in our applications based on our requirements.