C# Definite Assignment Analysis

This C# article investigates definite assignment analysis in a simple program.
Definite assignment. How does the C# language handle uninitialized local variables? It uses definite assignment analysis. This proves that all variables are assigned before they are used. This yields deterministic results. Quality improves.
Example. This first code example doesn't compile. The error the compiler gives is "Use of unassigned local variable i." The variable "i" is decremented, but it was never initialized to a value.

Therefore: You cannot determine the end result. If random bytes from memory are used to initialize "i", it could have any value.

C# program that does not compile using System; class Program { static void Main() { int i; int b = 10; while (b >= 0) { i--; b--; } Console.WriteLine(i); Console.WriteLine(b); } }
When programs do not have the same results each time they are run, bad things happen. For example, a memory region that happens to be used to initialize "i" might almost always be zero, so a programmer might think the program is correct.

However: In one situation the memory region might have another value, and the program would fail.

Example 2. Next, we look at the version of the above program that actually compiles. The variable "i" is initialized to 100. Thus, on every invocation of this program the variable i will end up with the value 89. It is deterministic.
C# program that compiles using System; class Program { static void Main() { int i = 100; int b = 10; while (b >= 0) { i--; b--; } Console.WriteLine(i); Console.WriteLine(b); } } Output 89 -1
Fields. Fields also participate in definite assignment analysis. However, you do not need to explicitly assign them anywhere. Their default value is set automatically when the enclosing type is allocated.

Tip: Numeric values that are fields are by default 0. Reference values are by default null.

So: It is wasteful to explicitly initialize fields to these values. This is an FxCop warning.

Ref, out. Definite assignment helps us with the ref and out keywords as well. In methods that use a formal out parameter, definite assignment analysis must prove the parameter is assigned before the method exits.Out

And: The ref keyword, on the other hand, must be assigned before it is passed to another method.

Summary. Definite assignment analysis is a key to understanding the C# language. In the specification, you can review the exact algorithm that language implementers must use. At every statement start and end, definite assignment is established.

So: In the end, this results in high-quality, deterministic programs that are less likely to fail.

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls