The C# compiler is a bit ... old fashioned ... and won't do static analysis. So it breaks on seemingly correct code like this:
MyStruct s;
bool inited = false;
foreach( Something foo in ACollection )
{
if( foo.Test() )
continue;
if( inited )
s.DoSomething();
else
{
s = foo.GetMeAnS();
inited = true;
}
}
Note: the unusual problem is that "s" is a struct. If it were a class, I'd simply init it to null. This struct has no meaningful "uninited" state, and I don't want to pay the performance cost of initing something I immediately throw away, just to satisfy a weak compiler.
The code (should be) fully correct: it's impossible to access s until s has been inited. (I've copy/pasted from actual code, but edited-out long method names for simplicity).
C# compiler in Mono used to allow this, but now it doesn't. Nothing has changed except the compiler, which now gives an error on unassigned variable.
Is there a code way to tell it to shut up and mind its own business? :) I don't want to fiddle with changing compiler-settings (if possible) because the code is compiled by other people/orgs - I'd prefer a code way of fixing the problem.
foreach(Something foo in ACollection.Where(f => !f.Test())) { MyStruct s = foo.GetMeAnS(); }This removes most of the code and is still doing the same. You don't need to declare it outside of the loop.