Search code examples
c#if-statementinitializationdeclaration

Why does this if statement not intialize or update my variable?


I'm a bit confused about declaring variables and then initializing/assigning those variables in a code block such as an if statement, then using that variable in the rest of my code.

The following example fails to assign the result of num1 + num2 to "result" in the if statement if "result" is declared and not initialized beforehand.

        int num1 = 1;
        int num2 = 2;
        int result; //declared

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //Use of unassigned local variable "result"

However, declaring and initializing "result" beforehand successfully updates the "result" value in the if statement.

        int num1 = 1;
        int num2 = 2;
        int result = 0; //declared and initialized

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //3

Moreover, if I change the condition in the if statement simply to "true" instead of "num1 == 1", then both of the previous examples work perfectly.

Could someone kindly explain this to me?


Solution

  • If the compiler can't determine that result is initialized before using, it will fail with error CS0165 (Use of unassigned local variable).

    Considering that num1 is not a constant, compiler can't guarantee that it stays 1 after the initialization and result = mu,1 + num2 will be executed. This example might look trivial, but it won't be difficult to change the code in a way that another thread can manipulate the values between the initialization of num1 and the check. But when you change the condition to true, then the compiler can determine that result will always be initialized prior to the usage, hence it compiling.

    Similarly, when result is initialized to zero at declaration, then again compiler has a guarantee that it is initialized prior to usage.