C# Keywords

C# Keywords

C# contains reserved words that have special meaning for the compiler. These reserved words are called "keywords". 

Keywords cannot be used as an identifier (name of a variable, class, interface, etc.).

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error.

In C# keywords cannot be used as identifiers. However, if we want to use the keywords as identifiers, we may prefix the keyword with @ character. For example, @switch is a valid identifier, but the switch is not because it’s a keyword and having a special meaning for the compiler.

Example of using the reserved keywords as variable names by including @ as a prefix in c# programming language:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    public class @class
    {
        public int age;
    }
    class Program
    {
        static void Main(string[] args)
        {
            @class p = new @class();
            p.age = 22;
            Console.WriteLine("Age: " + p.age + " years old :)");
            Console.ReadLine();
        }
    }
}

Output:

C# keywords

 

Types of Keywords:

There is two types of keywords in C#:

  • Reserve Keywords
  • Contextual Keywords

 

A - Reserved keywords

Reserved keywords in C# are reserved for the compiler in any part of the program.

A list of Reserved Keywords available in C# programming language is given below:

abstractboolcontinuedecimaldefaulteventdelegate
explicitexterncharcheckedclassconstis
breakasbaselongnumbytelock
casecatchfalsefinallyfixedfloatfor
foreachifininterfaceinternaldodouble
gotoimplicitintelsenamespacenewnull
objectoperatoroutoverrideparamsprivateprotected
ulongpublicreadonlysealedshortsizeofstring
uintrefreturnsbytestackallocstaticstruct
voidvolatilewhiletruetryswitchthis
throwuncheckedunsafeushortusingusingstatic
virtualtypeofout (generic modifier)in (generic modifier)

Some identifiers which have special meaning in context of code are called as Contextual Keywords.

Keywords in C# is mainly divided into 10 categories as follows:

  1. Value Type Keywords
  2. Reference Type Keywords
  3. Modifiers Keywords
  4. Statements Keywords
  5. Method Parameters Keywords
  6. Namespace Keywords
  7. Operator Keywords
  8. Conversion Keywords
  9. Access Keywords
  10. Literal Keywords

1 - Value Type Keywords

Type keywords are used for data types.

There are 15 keywords in value types which are used to define various data types: bool, byte,  char, decimal, doubleenum, float, int, long, sbyte, short, struct, unit, ulongushort.

All these keywords are used to specify the type of variable. When you specify a type of a variable, you tell the compiler the type of values that variable can store. For exapmle, int can store integer values and not strings.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // here byte is keyword a is identifier
            byte a = 68;
            Console.WriteLine("The value of a is: {0}", a);

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

            Console.WriteLine("The value of b is: {0}", b);
            Console.ReadLine();
        }
    }
}

Output:

C# Type Keywords Example

2 - Reference Type Keywords

There are 6 keywords in reference types which are used to store references of the data or objects. The keywords in this category are: class, delegate, interface, object, string, void.

3 - Modifiers Keywords

Modifier keywords are specific keywords that indicate who can modify types and type members. 

Modifiers allow or prevent certain parts of programs from being modified by other parts.

There are 17 keywords in modifiers which are used to modify the declarations of type member.

publicprivateinternalprotectedabstractconst
eventexternnewoverridepartialreadonly
sealedstaticunsafevirtualvolatile

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        class Agent
        {
            // using public modifier keyword
            public int age;
        }
        static void Main(string[] args)
        {
            Agent obj1 = new Agent();
            // access to public members
            obj1.age = 37;

            Console.WriteLine("Value of age: {0}", obj1.age);
            Console.ReadLine();
        }
    }
}

Output:

C# Modifiers Keywords Example

4 - Statements Keywords

C# Statement keywords are related to program flow.

There are total 18 keywords which are used in program instructions.

ifelseswitchdoforforeach
inwhilebreakcontinuegotoreturn
throwtrycatchfinallycheckedunchecked

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // using for as statement keyword
            for (int i = 1; i < 3; i++)
            {
                // here if and continue are keywords
                if (i == 2)
                    continue;
                Console.WriteLine("[X] Developer Space");
            }
            Console.ReadLine();
        }
    }
}

Output:

C# Statements Keywords Example

5 - Method Parameters Keywords

These keywords are applied to the parameters of a method.

There are total 4 keywords which are used to change the behavior of the parameters that passed to a method. The keyword includes in this category are:

paramsinrefout

6 - Namespace Keywords

These keywords are applied with namespace and related operators.

There are total 3 keywords in this category which are used in namespaces. 

The keywords are:

namespaceusingextern

7 - Operator Keywords

Operator keywords perform miscellaneous actions.

There are total 8 keywords which are used for different purposes like creating objects, getting a size of object etc. 

The keywords are:

asisnewsizeof
typeoftruefalsestackalloc

8 - Conversion Keywords

There are 3 keywords which are used in type conversions. 

The keywords are: explicit, implicit, operator.

9 - Access Keywords

There are 2 keywords which are used in accessing and referencing the class or instance of the class. The keywords are: base, this.

Access modifiers Keywords are applied to the declaration of the class, method, properties, fields, and other members. They define the accessibility of the class and its members.

Access ModifiersUsage
publicThe Public modifier allows any part of the program in the same assembly or another assembly to access the type and its members.
privateThe Private modifier restricts other parts of the program from accessing the type and its members. Only code in the same class or struct can access it.
internalThe Internal modifier allows other program code in the same assembly to access the type or its members. This is default access modifiers if no modifier is specified.
protectedThe Protected modifier allows codes in the same class or a class that derives from that class to access the type or its members.

10 - Literal Keywords

Literal keywords apply to the current instance or value of an object.

There are 2 keywords which are used as literal or constant. 

The keywords are: null, default.

 

B - Contextual keywords

These are used to give a specific meaning in the program. Whenever a new keyword comes in C#, it is added to the contextual keywords, not in the keyword category.

Generally, whenever the new keywords are added to the C# language, those are treated as Contextual keywords to avoid breaking c# programs that we wrote in older versions.

A list of Contextual Keywords available in C# programming language is given below:

addaliasascendingasyncawaitbydynamic
equalsfromdescendinggetglobalgroupinto
joinletnameofonorderbyremoveselect
setvaluevarwhenwherewhereyield
partial(type)partial(method)

Notes:

  • These are not reserved words.
  • There are total 30 contextual keywords in C#.
  • These can have different meanings in two or more contexts.
  • It can be used as identifiers outside the context that’s why it named contextual keywords.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    public class Student
    {

        // Declare name field 
        private string name = "Hello World From XDevSpace";

        // Declare name property 
        public string Name
        {

            // get is contextual keyword
            get
            {
                return name;
            }

            // set is a contextual
            // keyword
            set
            {
                name = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();

            // calls set accessor of the property Name, 
            // and pass "DANI" as value of the 
            // standard field 'value'. 
            s.Name = "DANI";

            // displays DANI, Calls the get accessor 
            // of the property Name. 
            Console.WriteLine("Name: " + s.Name);

            // using get and set as identifier
            int get = 60;
            int set = 90;

            Console.WriteLine("Value of get is: {0}", get);
            Console.WriteLine("Value of set is: {0}", set);
            Console.ReadLine();
        }
    }
}

Output:

C# Contextual keywords