Search code examples
c#language-designlocal-variables

Compiler error - "use of unassigned local variable". what can go wrong?


Almost every blog I read says compiler flagging error "use of unassigned local variable" says its design decision because history says that unassigned variable are source of bug and compiler wants to stop you doing that.

I am not sure how assigning to a local variable can help me not injecting a bug or even mitigate the chances of introducing bug.

I could have assigned a local variable as a return value of some method that can have bug and eventually result in wrong assignment. So I don't think compiler is helping me in that sense anyway. Had been designers decided to consider default value for unassigned local variables, developers would have taken care of it and in context of "possibly introducing bug" situation would have been same, no ?

Thanks!!


Solution

  • The use of an unassigned variable can be a potential bug or not (it almost always is). The question here is; if it is a bug, when would you like to know about it? At compile time or at runtime where it can be relatively hard to spot if the code is sufficiently complex or the introduced bug is subtle?

    A simple example:

    string Join(params object[] array)
    {
        string foo;
    
        foreach (var o in arr)
            foo += o.ToString();
    }
    

    So now, we have two options: the compiler lets you compile this happily and watches you crash and burn in runtime, or it tells you straightaway you have bug. The latter choice seems better to me.

    Now, when you wrote this question, you were probably thinking in value types more than in reference types; an unassigned reference type is practically an immediate NullReferenceException and, although vexing, easy to fix once you run the code for the first time.

    Value types on the contrary have usable default values, but that makes the situation a whole lot worse. Now maybe you forgot to initialize a variable to a sensible value and nothing apparently obvious is going wrong in runtime but maybe you've just introduced a not so obvious bug in your program:

    int totalDays(DateTime date)
    {
        DateTime now; //TODO: initialize to server time, not local DateTime.Now
        return (now - date).TotalDays;
    }
    

    Writing this code you spill your coffee, then you get a phone call from you wife telling you your dog got sick and puked on your favorite (and expensive) rug and again on the way to the vet in your brand new car... by the time you get back you've forgotten about totalDays (I finished writing it didn't I?) and you start working on other stuff in your project. By the end of the day/week, you need to meet a deadline and you ship a bug in your code. The compiler can warn you easily that something smelly is going on. Why on earth wouldn't you want it to?

    Convinced?