Search code examples
c#.netvalue-typereference-type

What is the value for local variables before the assignment?


I know that the default value for reference types is null and the default value for value types follow this table: http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx.

I also know that in C#, instance fields are automatically initialized and local variables are not. I'm also aware that the compiler will force you to assign a local variable before you read it.

I'm curious about what is the value of a local variable before it's assigned. Is it set to the default value, even though the compiler wants you to explicitly assign a value, or is it just random bits?


Solution

  • It actually depends on an IL flag. The MS C# compiler currently always sets this flag, so the memory is actually set to zero. However, technically there is no reason for it to do so. Either way, it is an implementation detail: you cannot find the answer to this using just C#, since C# will not allow you to query the value (directly or indirectly) of a local that is not "definitely assigned" (but you can if you use ILGenerator or similar to create a method directly in IL).

    The flag specifically is the init in .locals init (...)

    Edit: clarification - the CLI specification requires that all verifiable methods have .locals init, not just .locals: so without this, the code would not be verifiable, even if it was correct.