I was quite suprised today to discover that I can't do the following.
public class NumberyStuff
{
public List<int> Numbers { get; set; }
public int Total { get; set; }
}
var numbers = new NumberyStuff
{
Numbers = new List<int>{ 1, 2, 3, 4, 5 },
Total = Numbers.Sum() // "Numbers does not exist in the current context"
}
Am I just missing some syntax? Or is this impossible?
This is impossible, you need to move the total setting out of the object construction:
If you actually disassemble and look at the generated code for the initialisation of the Numbers property, you'll see that it is all done through temp variables.
While I guess there should be no technical reason that you can't generate the sum from the <>g__initLocal1 variable, there is no syntax available for you to access it until after it has been placed in the numbers object.