Why is this C# code not compiling?
public static Dictionary<short, MemoryBuffer> GetBulkCustom(int bufferId,
int startSecond,out int chunksize, out int bardatetime)
{
//const string _functionName = "GetNextBulkWatchData";
UserSeriesCard currentCard = GetUserSeriesCard(bufferId);
Dictionary<short, MemoryBuffer> result = null;
while (currentCard.CurrentSecond <= startSecond)
result = GetBulk(bufferId, out chunksize, out bardatetime);
if (result == null)
{
result = currentCard.UserBuffer;
chunksize = currentCard.ChunkSize;
bardatetime = currentCard.CurrentBarDateTime;
}
return result;
}
Errors:
The out parameter 'bardatetime' must be assigned to before control leaves the current method
The out parameter 'chunksize' must be assigned to before control leaves the current method
I can’t think of a case where bardatetime and chunksize will end up unassigned..
Edit. I fixed this error by adjusting the code to a logically equivalent one. Honestly I wanted to avoid multiple assigments.
public static Dictionary<short, MemoryBuffer> GetBulkCustom(int bufferId, int startSecond,out int chunksize, out int bardatetime )
{
const string _functionName = "GetNextBulkWatchData";
UserSeriesCard currentCard = GetUserSeriesCard(bufferId);
Dictionary<short, MemoryBuffer> result = null;
chunksize = currentCard.ChunkSize;
bardatetime = currentCard.CurrentBarDateTime;
while (currentCard.CurrentSecond <= startSecond)
result = GetBulk(bufferId, out chunksize, out bardatetime);
if (result == null)
result = currentCard.UserBuffer;
return result;
}
If the while loop and “if statement” bodies are never entered then the out parameters are not assigned.
It might be the case that logically you know that those code paths will always be entered. The compiler does not know that. The compiler believes that every “if” and “while” that has a not-constant condition can be entered or skipped.
The compiler could in this case do a more sophisticated flow analysis. The analysis is “before the ‘if’, result is either null or not null; if it is null then the ‘if’ body assigns the out parameters. If it is not null then the only way that could have happened is if the ‘while’ body assigned the out parameters, therefore the out parameters are assigned.”
That level of analysis is certainly possible, but the existing flow analysis algorithm described in the spec has some nice properties, namely that it is fast, easy to understand, easy to implement, usually accurate and only gives false positives, not false negatives.