Dependent fields when using object property initialisation in C#

252 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

Despite looking a bit like one, the initializer is not a ctor, and is in the context of the calling routine, so there is no this pointer. You would have to write something like:

// This doesn't work either.
var numbers = new NumberyStuff  
{  
     Numbers = new List<int>{ 1, 2, 3, 4, 5 },  
     Total = numbers.Numbers.Sum()   
}  

except, numbers is not assigned yet.