4

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.)

Michael Edenfield
  • 28,070
  • 4
  • 86
  • 117
  • 4
    There are most certainly far more readable, maintainable, and scalable solutions to this problem, even if this travesty will in fact reliably work. – Servy Feb 27 '15 at 21:32
  • @Servy I totally agree, and I already have one written that replicates the behavior, but this is an area that requires a good bit of QA (it's a report so our automated tests suck at it) and I want to have a good reason to add the QA time. – Michael Edenfield Feb 27 '15 at 21:35
  • 1
    @dotctor not sure how i missed that but thanks! – Michael Edenfield Feb 27 '15 at 21:44

0 Answers0