C# › Fundamentals
How does the C# compiler enforce 'definite assignment' analysis, and what compile error results from violating it?
AdvancedAnswer
The compiler statically tracks whether a LOCAL variable is GUARANTEED to have been assigned a value along EVERY possible code path before it's read — if there's any path where it might be used before assignment (like an unassigned variable inside an 'if' with no corresponding 'else'), the compiler raises a 'Use of unassigned local variable' error, catching a whole class of bugs before runtime.
int result;
if (someCondition) {
result = 10;
}
// Console.WriteLine(result); // Error: 'result' might not be assigned if someCondition was falseReal-world example Understanding why the compiler sometimes flags seemingly-fine code as an error, tracing it back to a code path where a variable genuinely might be unassigned.