A Gentle Introduction to Definite Assignment

A significant part of the language specification deals with rules of definite assignment, in short to ensure a variable is not used before it has been assigned to. Use of unassigned variables has been a historical source of many bugs, and C# wants to avoid these kinds of mishaps.

Let’s set the scene by looking at some simple native C/C++ code. What will the following code print to the screen?

void main(){    int x;    printfn("%d\n", x);}

Before answering, notice the code will compile fine. In fact, some C/C++ compilers (for example, Microsoft’s) will raise a red flag by emitting a warning:

warning C4700: uninitialized local variable 'x' used

But warnings can be ignored. As you will see, in C# this ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.