I have just encountered something quite bizarre running an app in Debug
mode (VS 2008 Express
, Any Cpu
). I would appreciate if someone enlightened me as to what is happening here?
// PredefinedSizeGroupMappings is null here
Dictionary<string, int> groupIDs = PredefinedSizeGroupMappings ?? new Dictionary<string, int>();
// so groupIDs is now initialized as an empty Dictionary<string, int>, as expected
// now: PredefinedSizesMappings is null here - therefore I expect sizeIds
// to be initialized as an empty dictionary:
Dictionary<string, string> sizeIds = PredefinedSizesMappings ?? new Dictionary<string, string>();
// but at this point sizeIds is still null! :O That's what debugger shows.
var groupsReport = new AutomappingReportArgs();
// only once we get here - it's suddenly not... The debugger shows: "Count = 0"
var sizesReport = new AutomappingReportArgs();
The AutomappingReportArgs
class has no connection whatsoever to the sizeIds
variable, although its constructor does alocate a number of dictionaries:
public AutomappingReportArgs()
{
ChangedNames = new Dictionary<string, KeyValuePair<string, string>>();
CreatedAfterRename = new Dictionary<string, string>();
Existing = new Dictionary<string, string>();
Created = new Dictionary<string, string>();
Failed = new Dictionary<string, string>();
}
I guess it must be some sort of compiler or CLR optimization, but I would like to know the mechanism of it in more detail. What is the reason for this "deferred initialization"?
And why is it inconsistent, why does it work straight away for Dictionary<string, int>
, but not for Dictionary<string, string>
? Is it because the compiler can't see any Dictionary<string, int>
initialization ahead, so it can't put it aside for later?