Reputation: 11549
Below method compiles fine.
string DoSomething(int x) {
string s;
if(x < 0)
s = "-";
else if(x > 0)
s = "+";
else
return "0";
return DoAnotherThing(s);
}
But when I write same code within a foreach
loop and use yield return
instead of return
I get Use of unassigned local variable 's'
compile error.
// Causes compile error
IEnumerable<string> DoSomethingWithList(IEnumerable<int> xList) {
foreach(var x in xList) {
string s;
if(x < 0)
s = "-";
else if(x > 0)
s = "+";
else
yield return "0";
// COMPILE ERROR: Use of unassigned local variable 's'
yield return DoAnotherThing(s);
}
}
For me, it is so obvious s
is assigned when code reached that line. What may be the cause for this error, may it be a compiler bug?
Upvotes: 2
Views: 1031
Reputation: 34200
This isn't a compiler bug. (There are very few of those around, really, so the chances of hitting one are small.) It's a quite simple bug in your code.
When the value of x
is zero, your code enters the else
block and yields "0"
. When the next value is requested, the method continues and executes this line:
yield return DoAnotherThing(s);
... and you have not assigned any value to s
at this point.
Upvotes: 7
Reputation:
If x
is equal to zero, s
is never assigned. So you're passing an unassigned variable to DoAnotherThing()
.
It's possible you want yield break
in the else clause. Keep in mind that yield return
does not return the same way as a normal function. It returns one item, but allows you to keep iterating. yield break
stops iterating.
Upvotes: 3