Wednesday, October 17, 2007

Unknown, Yet Powerful Keywords of C#

As a C# developer you would have learned many keywords which you might have used many times. But there are few keywords which are known to very few developers and rarely used by them. I would like to tell you about few such keywords which i came across few days ago.

stackalloc: The keyword stackalloc is used to dynamically allocate memory in the stack. Memory allocated using stackalloc keyword provides very quick access and the memory is released as soon the enclosing function exits.

int * fPtr = stackalloc int[100];

volatile: The keyword volatile is used to declare variables which are accessed and modified by multiple threads. When a variable is declared as volatile, compiler does not subject the code associated with the variable for optimizations that assume access by a single thread.

private volatile int sIntanceCounter;

default: Default keyword is used to assign the default value to a generic paramter when we dont know the type of the generic parameter.

public T GetNext()
//T is a generic type
T temp = default(T);
// Generic code;
return temp;