Is CS0165 C# compiler error guaranteed for unassigned local variables?

In code like this:

int val;

if (something())
   val = 10;

val++; // Error CS0165 Use of unassigned local variable

I get CS0165 error message when a local variable is used when there's a chance it was not surely initialized before.

In C++ world this scenario is undefined behavior class situation, which means that anything is allowed. So maybe there's a compiler error, maybe there's a compiler warning, maybe there's a runtime error, maybe code just uses whatever was in memory at that moment and good luck noticing it.

Is CS0165 guaranteed for such code in C#?

Is there a case where this specific piece of code does not yield an error message?

Jon Skeet
people
quotationmark

Is CS0165 guaranteed for such code in C#?

Yes, the rules of definite assignment are designed so that a local variable can never be read before it's definitely been written.

It's pretty conservative, too - for example:

bool condition = false;
int x;
if (condition)
{
    x = 0;
}
if (!condition)
{
    x = 1;
}
Console.WriteLine(x); // Error

Here even though we know that exactly one of those if statement bodies will be entered, the compiler doesn't - so x isn't definitely assigned at the end.

The rules of definite assignment are in the C# 5 specification in section 5.3.

Note that various classes of variables (e.g. static fields, and instance fields of classes) are deemed "initially assigned" - but they have well-specified default values, so there's still no undefined behaviour there.

people

See more on this question at Stackoverflow