Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
antonv Avatar asked Jan 18 '14 21:01

antonv


2 Answers

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.

like image 193
Mzf Avatar answered Oct 06 '22 11:10

Mzf


It's described in c# spec:

5.1.7 Local variables

A local variable introduced by a local-variable-declaration is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable introduced by a local-variable-declaration is considered initially unassigned. A local-variable-declaration may include a local-variable-initializer, in which case the variable is considered definitely assigned only after the initializing expression (§5.3.3.4).

Within the scope of a local variable introduced by a local-variable-declaration, it is a compile-time error to refer to that local variable in a textual position that precedes its local-variable-declarator. If the local variable declaration is implicit (§8.5.1), it is also an error to refer to the variable within its local-variable-declarator.

like image 33
MarcinJuraszek Avatar answered Oct 06 '22 11:10

MarcinJuraszek