On 27-09-2011 18:21, Peter Duniho wrote:
> On 9/27/11 8:41 AM, Henning wrote:
>>
>> I'm completely new to C#, although I have some background in TurboPascal
>> many years ago.
>>
>> What I need is the explanation of why the first example gets and "use of
>> unassigned variable" when the variable is referenced outside the while
>> loop, while the second example works ok.
>
> The C# specification has precise rules regarding "definite assignment".
> Your first example does not meet the criteria required for the variable
> "checkvalue" to be considered "definitely assigned", hence the failure.
>
> The second example trivially meets the criteria, by assigning the
> variable at initialization.
>
> With respect to the first example, it's important to note that the C#
> specification does not require the compiler to do any analysis of loop
> conditions. So even though you as a human are aware that the loop is
> executed at least once, from the compiler's point of view all it knows
> is that there's a loop and that loop bodies can sometimes be skipped
> entirely. Since the only place the variable is definitely assigned is
> within the loop body, and the loop body can theoretically be skipped,
> the variable is considered to not be definitely assigned.
>
> You can download the v4 specification for C# here:
> http://www.microsoft.com/download/en...ang=en&id=7029
>
> Pete
Thanks for the concise and precise explanation.