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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.