Search code examples
c#propertiesobject-initialization

Dependent fields when using object property initialisation in C#


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?


Solution

  • This is impossible, you need to move the total setting out of the object construction:

    var numbers = new NumberyStuff
    {
         Numbers = new List<int>{ 1, 2, 3, 4, 5 }         
    }
    numbers.Total = numbers.Numbers.Sum();
    

    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.

    NumberyStuff <>g__initLocal0 = new NumberyStuff();
    List<int> <>g__initLocal1 = new List<int>();
    <>g__initLocal1.Add(1);
    <>g__initLocal1.Add(2);
    <>g__initLocal1.Add(3);
    <>g__initLocal1.Add(4);
    <>g__initLocal1.Add(5);
    <>g__initLocal0.Numbers = <>g__initLocal1;
    NumberyStuff numbers = <>g__initLocal0;
    

    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.