“Unassigned variable” error in C#

May 20th, 2007 at 6:16 pm

Today I was reading about the “unassigned variable” detection of the C# compiler. If you write this code:


int x;
Console.WriteLine(x);

The compiler generates an error: error CS0165: Use of unassigned local variable ‘x’. Naturally, I wanted to see how this feature fails, and not surprisingly:


int x;
int y = 1;

if (y == 1)
    x = 9;

Console.WriteLine(x);

Generates the same error. This was expected, of course - since the compiler will have to actually run the program to test for the “unassigned” condition in the general case (which is what happens, kind of, in dynamic interpreted languages like Ruby - where runtime and compile time refer to the same process).

Still, this error in C# is useful, since it can probably detect 99% of the real-world cases.

Related posts:

  1. A taxonomy of typing systems
  2. exceptions vs. error codes
  3. c++ woes: std:: and unwanted warnings
  4. Variable initialization in C++
  5. C -> Parrot compiler

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)