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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With