Search code examples
c#initializationdefault-valuelocal-variables

Why C# local variable should be assigned directly, even if it's default value?


If you look at next example:

public void TestLocalValuesAssignment()
{
    int valueVariable; // = default(int) suits fine
    string refType; // null suits fine as well

    try
    {
        valueVariable = 5;
        refType = "test";
    }
    catch (Exception){}

    Console.WriteLine("int value is {0}", valueVariable);
    Console.WriteLine("String is {0}", refType);
}

you could easily see, that variables valueVariable and refType could be unassigned before their usage in Console.WriteLine(). Compiler tells us about that with errors:

Error   1   Use of unassigned local variable 'valueVariable'
Error   2   Use of unassigned local variable 'refType'  

This is a widespread case and there are loads of answers on how to fix that (possible fixes commented).

What I can't understand is why such behavior exists? How here local variables are different from class fields, where last ones get default value if not assigned (null for reference types and correspondent default value for value types)? Maybe there's an example or a corner case that explains why such compiler behavior is chosen?


Solution

  • basically - this is what MS decided.

    If you want more you can read here and check Eric Lippert’s Blog

    The reason this is illegal in C# is because using an unassigned local has high likelihood of being a bug.