nordwindranger

planet temp;

int highest=0;

//create attack missions

while (enemyPlanets.Count > 0)

{

highest = 0;

foreach (planet p in enemyPlanets)

{

if (p.rating() > highest)

{

temp = p;

highest = p.rating();

}

}

error-----> enemyPlanets.Remove(temp);

attack_M.Add(new order(order.Type.attack,1,temp));

}

this code throws the error "use of unassigned local variable temp". I've read through it a couple times, and just don't see why this is a problem. No matter what, at least one "p" must be higher than zero, and therefore "temp" will point to it. Even if the "enemyPlanets" list was empty, or all of the planets return a rating lower than zero, this would show up as a runtime error, not a compiling error.

Any ideas (I know that code can be kind of confusing taken out of context. if it needs further clarification please let me know!)




Re: Visual C# Language "use of unassigned variable" error. puzzling

nordwindranger

whoops! I'm an idiot. the problem is that "temp" is pointing to a local variable "p" that no longer exists out of the context of the foreach loop. Amazing that it took me 20 minutes to figure that out. I will have to make temp a new planet object, and all will be well.

well hopefully this offers you some amusement, or clears up the problem for someone else.






Re: Visual C# Language "use of unassigned variable" error. puzzling

Marcelo Guerra - MSFT

Hi,

Your solution is right, but the problem is no the scope of the variable p. The problem is that the assignment is inside and if statement. This code will give the same error and i and x are on the same scope:

int i;

int x = 1;

if (x == 1)

{

i = x;

}

if (x != 1)

{

i = x;

}

Console.WriteLine(i);

This problem is called definite assignment and is explained in http://msdn.microsoft.com/library/default.asp url=/library/en-us/csspec/html/vclrfcsharpspec_5_3.asp





Re: Visual C# Language "use of unassigned variable" error. puzzling

nordwindranger

interesting. thanks for the linky and the clarification