I recently came across code in an application that does the equivalent of this:
var source = new List<string>();
source.AddRange(getSomeListData());
var index = source.Count > 10 ? source.Count - 10 : 0;
var target = new TargetObject
{
Line1 = source.Count > index ? source[index++] : string.Empty,
Line2 = source.Count > index ? source[index++] : string.Empty,
Line3 = source.Count > index ? source[index++] : string.Empty,
Line4 = source.Count > index ? source[index++] : string.Empty,
.
.
.
}
The goal here is to include the last 10 items from the source data in the output object (in our case, the last line is crucial). But we don't know how many lines of data will be present -- it could be as few as 1.
This code works, at the moment, because VS2013 is running the member initializers in source-code order, so the side-effect of each index++
happens in the correct order. However, I read through the C# 5 specification and I cannot find any guarantee that this will always be true. Is the order in which these members are initialized deterministic, or is the above code subject to breaking in some future version of VS and/or other C# compilers?
(I have an opportunity to change it now, if there's a risk, but I don't want to change the code just for the sake of change.)