JaK82

Hi All,

I seem to have great difficulty passing a variable out of a while loop that I have received from calling a method and using the out option.

The program wont compile and I get this message

*use of unassigned local variable*

-------------------------

temp = variable is the variable I have received from the method

and if I put

Console.WriteLine(temp) outside the while loop it does not work ubt if I put it in the while loop it does

Any Ideas

C



Re: Visual C# Language Problem ** Cannot pass a variable out of a while loop

theTroll527

Can you show us the code

theTroll




Re: Visual C# Language Problem ** Cannot pass a variable out of a while loop

JaK82

Hi There

Unfortunatly not,

It is for uni and I do not want to get done for plagurism, I only need the general idea behind it,

I have tried googling various sites about the use of scope in a while loop but found nothing.

Any ideas,

 

C





Re: Visual C# Language Problem ** Cannot pass a variable out of a while loop

Marcelo Guerra - MSFT

Hi,

If I understand your question correctly. You are dealing with definite assignment.

This code sample:

class C

{

static void F(out int i) { }

static bool Cond() { return true; }

static void Main(string[] args)

{

int i;

while (Cond())

{

C.F(out i);

}

Console.WriteLine(i);

}

}

Won't compile and will tell you that i is not assigned in the line:

Console.WriteLine(i);

That's because if Cond() always returned false, then this line will be hit with an undefined i. If you use this line inside the while and before de call of C.F(out i) then it will work because at that point the variable has been assigned by F.

To solve the problem you have to do:

int i = 0;

or some other value.

Hope this helps.