views:

32

answers:

2

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  A: 

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.

Martin Harris
that sucks. Do you know why the compiler doesn't handle this? Has Lippert or one of the other compiler gurus ever blogged about it do you know?
fearofawhackplanet
@fearofawhackplanet if one of your properties depend on another propperty why not enforce that relationship in the class instead of pushing that resposibility to the caller? and that might very well be the answer to your question
Rune FS
+2  A: 

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.

James Curran