Absolute newbie question

H

Henning

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.

[example1]
static void Main(string[] args) {
bool ok = true; int checkvalue;
while (ok) {
checkvalue = 5;
Console.WriteLine("checkvalue in while loop {0} ", checkvalue);
ok = false; }
Console.WriteLine("checkvalue after the while loop {0} ", checkvalue);
Console.ReadKey();

[example2]
static void Main(string[] args) {
bool ok = true; int checkvalue=0;
while (ok) {
checkvalue = 5;
Console.WriteLine("checkvalue in while loop {0} ", checkvalue);
ok = false; }
Console.WriteLine("checkvalue after the while loop {0} ", checkvalue);
Console.ReadKey();

It's not that I don't got a clue or assumption, but I need the exact and
correct explanation/definiton
 
H

Henning

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/details.aspx?displaylang=en&id=7029

Pete

Thanks for the concise and precise explanation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top