C# Programming/Keywords


C# 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 int interface
internal is lock long namespace
new null object operator out
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 var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where

Abstract classes may contain abstract members in addition to implemented ones. That is, while some of the methods and properties in an abstract class may be implemented, others (the abstract members) may have their signatures defined, but have no implementation. Concrete subclasses derived from an abstract class define those methods and properties.

The as keyword casts an object to a different type. It is therefore similar to the TypeA varA = (TypeA) varB syntax. The difference is that this keyword returns null if the object was of an incompatible type, while the former method throws a type-cast exception in that case.

See also

edit

The keyword base describes that you would like to refer to the base class for the requested information, not in the current instantiated class.

A base class is the class in which the currently implemented class inherits from. When creating a class with no defined base class, the compiler automatically uses the System.Object base class.

Therefore the two declarations below are equivalent.

public class MyClass
{
}

public class MyClass : System.Object
{
}

Some of the reasons the base keyword is used is:

  • Passing information to the base class's constructor
public class MyCustomException : System.Exception
{
     public MyCustomException() : base() {}

     public MyCustomerException(string message, Exception innerException) : base(message,innerException) {}

     // ......
}
  • Recalling variables in the base class, where the newly implemented class is overriding its behaviour
public class MyBaseClass
{
     protected string className = "MyBaseClass";
}

public class MyNewClass : MyBaseClass
{
     protected new string className = "MyNewClass";

     public override string BaseClassName
     {
          get { return base.className; }
     }
}
  • Recalling methods in the base class. This is useful when you want to add to a method, but still keep the underlying implementation.
// Necessary using's here

public class _Default : System.Web.UI.Page
{
     protected void InitializeCulture()
     {
          System.Threading.Thread.CurrentThread.CurrentUICulture =
                              CultureInfo.GetSpecificCulture(Page.UICulture);

          base.InitializeCulture();
     }
}


The bool keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Boolean. That is, it represents a value of true or false. Unlike in C++, whose boolean is actually an integer, a bool in C# is its own data type and cannot be cast to any other primitive type.

The keyword break is used to exit out of a loop or switch block.

break as used in a loop
int x;
 
while (x < 20){

   if (x > 10) break;

   x++;
}

The while loop would increment x as long as it was less than twenty. However when x is incremented to ten the condition in the if statement becomes true, so the break statement causes the while loop to be broken and execution would continue after the closing parentheses.

break as used in a switch block
int x;

switch (x)
    {
    case 0:
        Console.WriteLine("x is 0");
        break;
    case 1:
        Console.WriteLine("x is 1");
        break;
    case 2:
        // falls through
    case 3:
        Console.WriteLine("x is 2 or 3");
        break;
    }

When the program enters the switch block, it will search for a case statement that is true. Once it finds one, it will read any further statements printed until it finds a break statement. In the above example, if x is 0 or 1, the console will only print their respective values and then jump out of the statement. However, if the value of x is 2 or 3, the program will read the same proceeding statement(s) until it reaches a break statement. In order not to show anybody who reads the code that this handling for 2 is the same for three, it is good programming practice to add a comment like "falls through" after the falling-through cases.


The byte keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Byte. That is, it represents an 8-bit unsigned integer whose value ranges from 0 to 255.


The keyword case is often used in a switch statement.


The keyword catch is used to identify a statement or statement block for execution, if an exception occurs in the body of the enclosing try block. The catch clause is preceded by the try clause, and may optionally be followed by a finally clause.


The char keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Char. That is, it represents a Unicode character whose from 0 to 65,535.


The checked and unchecked operators are used to control the overflow checking context for integral-type arithmetic operations and conversions. It checks, if there is an overflow (this is default).

See also


The class keyword is used to declare a class.


The const keyword is used in field and local variable declarations to make the variable constant. It is thus associated with its declaring class or assembly instead of with an instance of the class or with a method call. It is syntactically invalid to assign a value to such a variable anywhere other than its declaration.

Further reading

The keyword continue can be used inside any loop in a method. Its affect is to end the current loop iteration and proceed to the next one. If executed inside a for, end-of-loop statement is executed (just like normal loop termination).


The decimal keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Decimal. That is, it represents a signed, 128-bit decimal number whose value is 0 or a decimal number with 28 or 29 digits of precision ranging either from to or from to .


The default keyword can be used in the switch statement or in generic code:[1]

  • The switch statement: Specifies the default label.
  • Generic code: Specifies the default value of the type parameter. This will be null for reference types and zero for value types.

References

edit
  1. "default (C# Reference)". http://msdn.microsoft.com/en-us/: MSDN. Retrieved 2011-08-09. {{cite web}}: External link in |location= (help)


The delegate keyword is used to declare a delegate. A delegate is a programming construct that is used to obtain a callable reference to a method of a class.


The do keyword identifies the beginning of a do ... loop.


The double keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Double. That is, it represents an IEEE 754, 64-bit signed binary floating point number whose value is negative 0, positive 0, negative infinity, positive infinity, not a number, or a number ranging either from   to   or from   to  .


The else keyword identifies a else clause of an if statement with the following syntax:

if-statement ::= "if" "(" condition ")" if-body "else" else-body
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

An else clause immediately follows an if-body. It provides code to execute when the condition is false. Making the else-body another if statement creates the common cascade of if, else if, else if, else if, else statements:

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

The above example only checks whether myNumber is less than 0, if myNumber is not 4. It in turn only checks whether myNumber%2 is 0, if myNumber is not less than 0. Since none of the conditions are true, it executes the body of the final else clause.


The enum keyword identifies an enumeration.


The event keyword is used to declare an event.


General

edit

When values are cast implicitly, the runtime does not need any casting in code by the developer in order for the value to be converted to its new type.

Here is an example, where the developer is casting explicitly:

// Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int) fNumber;

The developer has told the runtime, "I know what I'm doing, force this conversion."

Implicit casting means that runtime doesn't need any prompting in order to do the conversion. Here is an example of this.

// Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;

Keyword

edit

Notice that no casting was necessary by the developer. What is special about implicit, is that the context that the type is converted to is totally lossless i.e. converting to this type loses no information, so it can be converted back without worry.

The explicit keyword is used to create type conversion operators that can only be used by specifying an explicit type cast.

This construct is useful to help software developers write more readable code. Having an explicit cast name makes it clear that a conversion is taking place.

class Something 
{
  public static explicit operator Something(string s)
  {
     // Convert the string to Something
  }
}

string x = "hello";

// Implicit conversion (string to Something) generates a compile time error
Something s = x;

// This statement is correct (explicit type name conversion)
Something s = (Something) x;


The keyword extern indicates that the method being called exists in a DLL.

A tool called tlbimp.exe can create a wrapper assembly that allows C# to interact with the DLL like it was a .NET assembly i.e. use constructors to instantiate it, call its methods.

Older DLLs will not work with this method. Instead, you have to explicitally tell the compiler what DLL to call, what method to call and what parameters to pass. Since parameter type is very important, you can also explicitly define what type the parameter should be passed to the method as.

Here is an example:

using System;
using System.Runtime.InteropServices;

namespace ExternKeyword
{
     public class Program
     {
          static void Main()
          {
               NativeMethods.MessageBoxEx(IntPtr.Zero, "Hello there", "Caption here", 0, 0);
          }
     }
  
     public class NativeMethods
     {
          [DllImport("user32.dll")]
          public static extern MessageBoxEx(IntPtr hWnd, string lpText, string lpCaption, uint uType, short wLanguageId);
     }
}

The [DllImport("user32.dll")] tells the compiler which DLL to reference. Windows searches for files as defined by the PATH environment variable, and therefore will search those paths before failing.

The method is also static because the DLL may not understand how to be "created", as DLLs can be created in different languages. This allows the method to be called directly, instead of being instantiated and then used.


C# 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 int interface
internal is lock long namespace
new null object operator out
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 var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where

The false keyword is a boolean constant value.


The keyword finally is used to identify a statement or statement block after a try-catch block for execution regardless of whether the associated try block encountered an exception, and executes even after a return statement. The finally block is used to perform cleanup activities.


The fixed keyword is used to prevent the garbage collector from relocating a variable. You may only use this in an unsafe context.

fixed (int *c = &shape.color) {
  *c = Color.White; 
}

If you are using C# 2.0 or greater, the fixed may also be used to declare a fixed-size array. This is useful when creating code that works with a COM project or DLL.

Your array must be composed of one of the primitive types: bool, byte, char, double, float, int, long, sbyte, short, ulong, or ushort.

protected fixed int monthDays[12];


The float keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Single. That is, it represents a IEEE 754, 32-bit signed binary floating point number whose value is negative 0, positive 0, negative infinity, positive infinity, not a number, or a number ranging either from   to   or from   to  .


The for keyword identifies a for loop.


The foreach keyword identifies a foreach loop.

// example of foreach to iterate over an array
public static void Main() {
  int[] scores = new int [] { 54, 78, 34, 88, 98, 12 };

    int total = 0;
  foreach (int score in scores) {
      total += score;
  }

  int averageScore = total/scores.Length;
}


The goto keyword returns the flow of operation to the label which follows it. Labels can be created by putting a colon after any word. e.g.

thelabel:       // This is a label
 System.Console.WriteLine("Blah blah blah");
 goto thelabel; // Program flow returns to thelabel

The use of goto is very controversial, because, when used frivolously, it creates code that jumps from place to place and is disorganized and hard to read. It is rarely even necessary because the same thing can often be accomplished with a more organized for loop or while loop.

The if keyword identifies an if statement with the following syntax:

if-statement ::= "if" "(" condition ")" if-body ["else" else-body]
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

If the condition evaluates to true, the if-body executes. Curly braces ("{" and "}") allow the if-body to contain more than one statement. Optionally, an else clause can immediately follow the if-body, providing code to execute when the condition is false. Making the else-body another if statement creates the common cascade of if, else if, else if, else if, else statements:

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

The boolean expression used in an if statement typically contains one or more of the following operators:

Operator Meaning Operator Meaning
< less than > greater than
== equal to != not equal to
<= less than or equal to >= greater than or equal to
&& and || or
! not

See also else.

General

edit

When values are cast implicitally, the runtime does not need any casting in code by the developer in order for the value to be converted to its new type.

Here is an example, where the developer is casting explicitly:

// Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int) fNumber;

The developer has told the runtime, "I know what I'm doing, force this conversion."

Implicit casting means that runtime doesn't need any prompting in order to do the conversion. Here is an example of this.

// Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;

Notice that no casting was necessary by the developer. What is special about implicit is that the context that the type is converted to is totally lossless, i.e. converting to this type loses no information. So, it can be converted back without worry.

Keyword

edit

The keyword implicit is used for a type to define how to can be converted implicitly. It is used to define what types can be converted to without the need for explicit casting.

As an example, let us take a Fraction class, that will hold a nominator (the number at the top of the division), and a denominator (the number at the bottom of the division). We will add a property so that the value can be converted to a float.

public class Fraction
{
     private int nominator;
     private int denominator;

     public Fraction(int nominator1, int denominator1)
     {
          nominator = nominator1;
          denominator = denominator1;
     }

     public float Value { get { return (float)_nominator/(float)_denominator; } }

     public static implicit operator float(Fraction f)
     {
          return f.Value;
     }

     public override string ToString()
     {
          return _nominator + "/" + _denominator;
     }
}

public class Program
{
    [STAThread]
     public static void Main(string[] args)
     {
          Fraction fractionClass = new Fraction(1, 2);
          float number = fractionClass;

          Console.WriteLine("{0} = {1}", fractionClass, number);
     }
}

To re-iterate, the value it implicitally casts to must hold data in the form that the original class can be converted back to. If this is not possible, and the range is narrowed (like converting double to int), use the explicit operator.


The in keyword identifies the collection to enumerate in a foreach loop.

The in keyword may also be used in a query, e.g., 'from item in dataset'. Immediately following the contextual keyword from is a range variable representing one item in the dataset. The dataset to be queried is defined immediately following the contextual keyword in. See also ascending, descending, in, orderby, select, and where.


The int keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Int32. That is, it represents a 32-bit signed integer whose value ranges from -2,147,483,648 to 2,147,483,647.


The interface keyword is used to declare an interface. Interfaces provide a construct for a programmer to create types that can have methods, properties, delegates, events, and indexers declared, but not implemented.

It is a good programming practice to give interfaces differing names from classes that start with an I and/or finish with ...able, like IRun or Runnable or IRunnable.


The internal keyword is an access modifier used in field, method, and property declarations to make the field, method, or property internal to its enclosing assembly. That is, it is only visible within the assembly that implements it.


The is keyword compares an object to a type, and if they're the same or of the same "kind" (the object inherits the type), returns true. The keyword is therefore used to check for type compatibility, usually before casting (converting) a source type to a destination type in order to ensure that won't cause a type-cast exception to be thrown. Using is on a null variable always returns false.

This code snippet shows a sample usage:

System.IO.StreamReader reader = new StreamReader("readme.txt");
bool b = reader is System.IO.TextReader;

// b is now set to true, because StreamReader inherits TextReader


The lock keyword allows a section of code to exclusively use a resource, a feature useful in multi-threaded applications. If a lock to the specified object is already held when a piece of code tries to lock the object, the code's thread is blocked until the object is available.

using System;
using System.Threading;

class LockDemo
{
    private static int number = 0;
    private static object lockObject = new object();
    
    private static void DoSomething()
    {
        while (true)
        {
            lock (lockObject)
            {
                int originalNumber = number;
                
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep for a random amount of time
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep again
                
                Console.Write("Expecting number to be " + (originalNumber + 2).ToString());
                Console.WriteLine(", and it is: " + number.ToString());
                // without the lock statement, the above would produce unexpected results, 
                // since the other thread may have added 2 to the number while we were sleeping.
            }
        }
    }
    
    public static void Main()
    {
        Thread t = new Thread(new ThreadStart(DoSomething));
        
        t.Start();
        DoSomething(); // at this point, two instances of DoSomething are running at the same time.
    }
}

The parameter to the lock statement must be an object reference, not a value type:

class LockDemo2
{
    private int number;
    private object obj = new object();
    
    public void DoSomething()
    {
        lock (this) // ok
        {
            ...
        }
        
        lock (number) // not ok, number is not a reference
        {
            ...
        }
        
        lock (obj) // ok, obj is a reference
        {
            ...
        }
    }
}


The long keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Int64. That is, it represents a 64-bit signed integer whose value ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.


The namespace keyword is used to supply a namespace for class, structure, and type declarations.


The new keyword has two different meanings:

  1. It is an operator that requests a new instance of the class identified by its argument.
  2. It is a modifier that explicitly hides a member.

As an example, see the code below:

public class Car
{
    public void go()
    {
    }
}

Car theCar = new Car();       // The new operator creates a Car instance

int i = new int();            // Identical to … = 0;

public class Lamborghini : Car
{
    public new void go()      // Hides Car.go() with this method
    {
    }
}


The null keyword represents an empty value for a reference type variable, i.e. for a variable of any type derived from System.Object. In C# 2.0, null also represents the empty value for nullable value type variables.


The object keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Object. That is, it represents the base class from which all other reference types derive. On some platforms, the size of the reference is 32 bits, while on other platforms it is 64 bits.


The operator keyword allows a class to overload arithmetic and cast operators:

public class Complex
{
    private double re, im;
    
    public double Real
    {
        get { return re; }
        set { re = value; }
    }
    
    public double Imaginary
    {
        get { return im; }
        set { im = value; }
    }
    
    // binary operator overloading
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex() { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary };
    }
    
    // unary operator overloading
    public static Complex operator -(Complex c)
    {
        return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary };
    }
    
    // cast operator overloading (both implicit and explicit)
    public static implicit operator double(Complex c)
    {
        // return the modulus: sqrt(x^2 + y^2)
        return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2));
    }
    
    public static explicit operator string(Complex c)
    {
        // we should be overloading the ToString() method, but this is just a demonstration
        return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i";
    }
}

public class StaticDemo
{
    public static void Main()
    {
        Complex number1 = new Complex() { Real = 1, Imaginary = 2 };
        Complex number2 = new Complex() { Real = 4, Imaginary = 10 };
        Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12
        
        number3 = -number3; // number3 now has Real = -5, Imaginary = -12
        double testNumber = number3; // testNumber will be set to the absolute value of number3
        Console.WriteLine((string)number3); // This will print "-5 + -12i".
        // The cast to string was needed because that was an explicit cast operator.
    }
}

The out keyword explicitly specifies that a variable should be passed by reference to a method, and set in that method. A variable using this keyword must not be intialized before the method call to ensure the developer understand its intended effects. Using this keyword requires the called method to set the variable using this modifier before returning. Using out also requires the developer to specify the keyword even in the calling code, to ensure that it is easily visible to developers reading the code that the variable will have its value changed elsewhere, which is useful when analyzing the program flow.

An example of passing a variable with out follows:

void CallingMethod()
{
    int i;
    SetDependingOnTime(out i);
    // i is now 10 before/at 12 am, or 20 after
}

void SetDependingOnTime(out int iValue)
{
    iValue = DateTime.Now.Hour <= 12 ? 10 : 20;
}


C# 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 int interface
internal is lock long namespace
new null object operator out
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 var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where

The keyword override is use in declaring an overridden function, which extends a base class function of the same name.

Further reading

The keyword params is used to describe when a grouping of parameters are passed to a method, but the number of parameters are not important, as they may vary. Since the number isn't important, the params keyword must be the last variable in a method signature so that the compiler can deal with the parameters which have been defined first, before dealing with the params.

Here are examples of where it will, and will not work:

// This works
public static void AddToShoppingBasket(decimal total, params string[] items)
{
  // ....
}

// This works
public static void AddToShoppingBasket(decimal total, int totalQuantity, params string[] items)
{
  // ....
}


// THIS DOES NOT WORK                  <-------------------->
public static void AddToShoppingBasket(params string[] items, decimal total, int totalQuantity)
{
  // ....
}

A good example of this is the String.Format method. The String.Format method allows a user to pass in a string formatted to their requirements, and then many parameters for the values to insert into the string. Here is an example:

public static string FormatMyString(string format, params string[] values)
{
     string myFormat = "Date: {0}, Time: {1}, WeekDay: {1}";
     return String.Format(myFormat, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), DateTime.Now.DayOfWeek);
}

// Output will be something like:
//
// Date: 7/8/2007, Time: 13:00, WeekDay: Tuesday;
//

The String.Format method has taken a string, and replaced the {0}, {1}, {2} with the 1st, 2nd and 3rd parameters. If the params keyword did not exist, then the String.Format() would need an infinite number of overloads to cater for each case.

public string Format(string format, string param1)
{
  // .....
}

public string Format(string format, string param1, string param2)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3, string param4)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3, string param4, string param5)
{
  // .....
}

// To infinitum


The private keyword is used in field, method, and property declarations to make the field, method, or property private to its enclosing class. That is, it is not visible outside of its class.


The protected keyword is used in field, method, and property declarations to make the field, method, or property protected to its enclosing class. That is, it is not visible outside of its class.


The public keyword is used in field, method, and property declarations to make the field, method, or property public to its enclosing class. That is, it is visible from any class.


The readonly keyword is closely related to the const keyword at a glance, with the exception of allowing a variable with this modifier to be initialized in a constructor, along with being associated with a class instance (object) rather than the class itself.

The primary use for this keyword is to allow the variable to take on different values depending on which constructor was called, in case the class has many, while still ensuring the developer that it can never intentionally or unintentionally be changed in the code once the object has been created.

This is a sample usage, assumed to be in a class called SampleClass:

readonly string s;

SampleClass()
{
    s = "Hello!";
}


The ref keyword explicitly specifies that a variable should be passed by reference rather than by value.

A developer may wish to pass a variable by reference particularly in case of value types. If a variable is passed by reference, only a pointer is sent to a function in reality, reducing the cost of a method call in case it would involve copying large amounts of data, something C# does when normally passing value types.

Another common reason to pass a variable by reference is to let the called method modify its value. Because this is allowed, C# always enforces specifying that a value is passed by reference even in the method call, something many other programming languages don't. This let developers reading the code easily spot places that can imply a type has had its value changed in a method, which is useful when analyzing the program flow.

Passing a value by reference does not imply that the called method has to modify the value; see the out keyword for this.

Passing by reference requires the passed variable to be initialized.

An example of passing a variable by reference follows:

void CallingMethod()
{
    int i = 24;
    if (DoubleIfEven(ref i))
        Console.WriteLine("i was doubled to {0}", i); // outputs "i was doubled to 48"
}

bool DoubleIfEven(ref int iValue)
{
    if (iValue%2 == 0)
    {
        iValue *= 2;
        return true;
    }
    return false;
}


The return keyword is used to return execution from a method or from a property accessor. If the method or property accessor has a return type, the return keyword is followed by the value to return.


The sbyte keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.SByte. That is, it represents an 8-bit signed integer whose value ranges from -128 to 127.


The sealed keyword is used to specify that a class cannot be inherited from. The following example shows the context in which it may be used:

public sealed class
{
    ...
}

Notice: The sealed class inheritance is the same as that of a final class in Java.


The short keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.Int16. That is, it represents a 16-bit signed integer whose value ranges from -32,768 to 32,767.

The sizeof keyword returns how many bytes an object requires to be stored.

An example usage:

int i = 123456;

Console.WriteLine("Storing i, a {0}, requires {1} bytes, or {2} bits.",
i.GetType(), sizeof(i), sizeof(i)*8);

// outputs "Storing i, a System.Int32, requires 4 bytes, or 32 bits."

The keyword stackalloc is used in an unsafe code context to allocate a block of memory on the stack.

int* fib = stackalloc int[100];

In the example above, a block of memory of sufficient size to contain 100 elements of type int is allocated on the stack, not the heap; the address of the block is stored in the pointer fib. This memory is not subject to garbage collection and therefore does not have to be pinned (via fixed). The lifetime of the memory block is limited to the lifetime of the method in which it is defined (there is no way to free the memory before the method returns).

stackalloc is only valid in local variable initializers.

Because Pointer types are involved, stackalloc requires unsafe context. See Unsafe Code and Pointers.

stackalloc is similar to _alloca in the C run-time library.

Note* - From MSDN


The static keyword is used to declare a class or a class member (method, property, field, or variable) as static. A class that is declared static has only static members, and these are associated with the entire class instead of class instances.


The string keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for System.String. That is, it indicates an immutable sequence of characters.


The struct keyword declares a structure, i.e. a value type that functions as a light-weight class.


The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body.

This is an example of a switch statement:

int currentAge = 18;

switch (currentAge)
{
case 16:
    Console.WriteLine("You can drive!");
    break;
case 18:
    Console.WriteLine("You're finally an adult!");
    break;
default:
    Console.WriteLine("Nothing exciting happened this year.");
    break;
}
Console Output
You're finally an adult! 	


The this keyword is used in an instance method or instance property to refer to the current class instance. That is, this refers to the object through which its containing method or property was invoked. It is also used to define extension methods.


The throw keyword is used to throw an exception object.

The true keyword is a Boolean constant value. Therefore

 while(true)

would create an infinite loop.


The try keyword is used to identify a statement or statement block as the body of an exception handling sequence. The body of the exception handling sequence must be followed by a catch clause, a finally clause, or both.

try 
{
    foo();
} 
catch(Exception Exc)
{
    throw new Exception ("this is the error message", Exc);
}

The typeof keyword returns an instance of the System.Type class when passed a name of a class. It is similar to the sizeof keyword in that it returns a value instead of starting a section (block) of code (see if, try, while).

An example:

using System;

namespace MyNamespace
{
    class MyClass
    {
        static void Main(string[] args)
        {
            Type t = typeof(int);
            Console.Out.WriteLine(t.ToString());
            Console.In.Read();
        }
    }
}

The output will be:

System.Int32

It should be noted that unlike sizeof, only class names themselves and not variables can be passed to typeof as shown here:

using System;

namespace MyNamespace
{
    class MyClass2
    {
        static void Main(string[] args)
        {
            char ch;
            
            // This line will cause compilation to fail
            Type t = typeof(ch);
            Console.Out.WriteLine(t.ToString());
            Console.In.Read();
        }
    }
}

Sometimes, classes will include their own GetType() method that will be similar, if not identical, to typeof.


The uint keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.UInt32. That is, it represents a 32-bit unsigned integer whose value ranges from 0 to 4,294,967,295.


The ulong keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.UInt64. That is, it represents a 64-bit unsigned integer whose value ranges from 0 to 18,446,744,073,709,551,615.

</noinclude>

The unchecked keyword prevents overflow-checking when doing integer arithmetics. It may be used as an operator on a single expression or as a statement on a whole block of code.

int x, y, z;
x = 1222111000;
y = 1222111000;

// used as an operator
z = unchecked(x*y);

// used as a statement
unchecked {
  z = x*y;
  x = z*z;
}


The unsafe keyword may be used to modify a procedure or define a block of code which uses unsafe code. Code is unsafe if it uses the "address of" (&) or pointer operator (*).

In order for the compiler to compile code containing this keyword, you must use the unsafe option when using the Microsoft C-Sharp Compiler.

class MyClass {
  public static void Main() {
    int x = 2;
    // example of unsafe to modify a code block
    unsafe {
      DoSomething(&x);
    }
  }

  // example of unsafe to modify a procedure
  unsafe static void DoSomething(int *msg) {
    Console.WriteLine(*msg);
  }
}


The ushort keyword is used in field, method, property, and variable declarations and in cast and typeof operations as an alias for the .NET Framework structure System.UInt16. That is, it represents a 16-bit unsigned integer whose value ranges from 0 to 65,535.


The using keyword has two completely unrelated meanings in C#, depending on if it is used as a directive or a statement.

The directive

edit

using as a directive resolves unqualified type references so that a developer doesn't have to specify the complete namespace.

Example:

using System;
 
// A developer can now type ''Console.WriteLine();'' rather than ''System.Console.WriteLine()''.

using can also provide a namespace alias for referencing types.

Example:

using utils = Company.Application.Utilities;

The statement

edit

using as a statement automatically calls the dispose on the specified object. The object must implement the IDisposable interface. It is possible to use several objects in one statement as long as they are of the same type.

Example:

using (System.IO.StreamReader reader = new StreamReader("readme.txt"))
{
    // read from the file
}
 
// The file readme.txt has now been closed automatically.

using (Font headerFont = new Font("Arial", 12.0f),
            textFont = new Font("Times New Roman", 10.0f))
{
    // Use headerFont and textFont.
}

// Both font objects are closed now.


The var keyword can be used in place of a type when declaring a variable to allow the compiler to infer the type of the variable. This feature can be used to shorten variable declarations, especially when instantiating generic types, and is even necessary with LINQ expressions (since queries may generate very complex types).

The following:

int num = 123;
string str = "asdf";
Dictionary<int, string> dict = new Dictionary<int, string>();

is equivalent to:

var num = 123;
var str = "asdf";
var dict = new Dictionary<int, string>();

var does not create a "variant" type; the type is simply inferred by the compiler. In situations where the type cannot be inferred, the compiler generates an error:

var str; // no assignment, can't infer type

void Function(var arg1, var arg2) // can't infer type
{
    ...
}

Note: Var is not a keyword


The keyword virtual is applied to a method declaration to indicate that the method may be overridden in a subclass. If the virtual keyword is not applied and a method is defined in a subclass with the same signature as the one in the parent class, the method in the parent class is hidden by the subclass implementation. With other words, it is only possible to have a true polymorphism of functions with this keyword.

Notice: Comparing it with Java, a method is not virtual if and only if it is final. This is the result of different design philosophies.


The void keyword is used in method signatures to declare a method that does not return a value. A method declared with the void return type cannot provide any arguments to any return statements they contain.

Example:

public void WorkRepeatedly (int numberOfTimes)
{
    for(int i = 0; i < numberOfTimes; i++)
        if(EarlyTerminationIsRequested)
            return;
        else
            DoWork();
}


The volatile keyword is used to declare a variable that may change its value over time due to modification by an outside process, the system hardware, or another concurrently running thread.

You should use this modifier in your member variable declaration to ensure that whenever the value is read, you are always getting the most recent (up-to-date) value of the variable.

class MyClass
{
  public volatile long systemclock;
}


This keyword has been part of the C# programming language since .NET Framework 1.1 (Visual Studio 2003).


The while keyword identifies a while loop.

Special C# Identifiers


The add and remove keywords allow you to execute code whenever a delegate is added or removed from an event. Its usage is similar to the get and set keywords with properties:

public event MyDelegateType MyEvent
{
    add
    {
        // here you can use the keyword "value" to access the delegate that is being added
        ...
    }
    
    remove
    {
        // here you can use the keyword "value" to access the delegate that is being removed
        ...
    }
}

The code in the add block will be executed when a delegate is added to the event. Similarly, the code in the remove block will be executed when a delegate is removed from the event.


The alias keyword is used to indicate an external alias.

When you need to use several versions of the same assembly or assemblies with the same full qualified typenames, you need to use the alias and extern keywords to give different alias names for each version.

Example:

extern alias AppTools;
extern alias AppToolsV2;

To use the typenames of each version, you have the operator :: .

Example:

AppTools::MainTool tool_v1 = new AppTools::MainTool();
AppToolsV2::MainTool tool_v2 = new AppToolsV2::MainTool();

However, this only says to the compiler that there are several assemblies with typename conflicts. To relate what of each assemblies match's the alias name, you have to tell the compiler on its options apart the source. On dotNet command line, this options would be:

/r:AppTools=AppToolsv100.dll /r:AppToolsV2=AppToolsv200.dll

Notice: In order for it to be of use, you need to provide an external assembly to the compiler (e.g. pass /r:EXTALIAS=XXX.dll) and identify the external alias within the code (e.g. extern alias EXTALIAS;)


The special identifier get is used to declare the read accessor for a property.


The global keyword is useful in some contexts to resolve ambiguity between identifiers. If you have a conflict between a class name and a namespace, for example, you can use the global keyword to access the namespace:

namespace MyApp
{
    public static class System
    {
        public static void Main()
        {
            global::System.Console.WriteLine("Hello, World!");
            // if we had just used System.Console.WriteLine, 
            // the compile would think that we referred to a 
            // class named "Console" inside our "System" class.
        }
    }
}

global does not work in the following situation, however, as our System class does not have a namespace:

public static class System
{
    public static void Main()
    {
        global::System.Console.WriteLine("Hello, World!");
        // "System" doesn't have a namespace, so the above
        // would be referring to this class!
    }
}


The special identifier partial is used to allow developers to build classes from different files and have the compiler generate one class, combining all the partial classes. This is mostly useful for separating classes into separate blocks. For example, Visual Studio 2005 separates the UI code for forms into a separate partial class that allows you to work on the business logic separately.


The special identifier set is used to declare the write accessor for a property.


The special identifier value is used in a property's write accessor to represent the value requested for assignment to the property.


The where keyword has two different meanings:

  1. It is used to specify one or more constraints on generic type parameters.
  2. With LINQ, it is used to query a data source and select or filter elements to return.


The yield keyword returns the next value from an iterator or ends an iteration.

Notes

edit

The reference list of C# keywords is at [2].