Assuming these initialization instructions compile
List<int> l = new List<int> { 1, 2, 3 };
Dictionary<int, int> d = new Dictionary<int, int> { [1] = 11, [2] = 22 };
Foo f = new Foo { Bar = new List<int>() };
and it will not be
List<int> l = { 1, 2, 3 };
Dictionary<int, int> d = { [1] = 11, [2] = 22 };
Foo f = { Bar = new List<int>() };
I have a question about nested initializations. Given the following class
public class Foo {
public List<int> Bar { get; set; } = new List<int>();
public Dictionary<int, Foo> Baz { get; set; } = new Dictionary<int, Foo>();
}
I accidentally discovered that you really can do this:
Foo f = new Foo {
Bar = { 1, 2, 3 },
Baz = {
[1] = {
Bar = { 4, 5, 6 }
}
}
};
While it compiles, it produces KeyNotFoundException. So I changed the properties to
public List<int> Bar { get; set; } = new List<int> { 4, 5, 6 };
public Dictionary<int, Foo> Baz { get; set; }
= new Dictionary<int, Foo> { [1] = new Foo { Bar = new List<int>() { 1, 2, 3 } } };
assuming this is an unusual notation to replace existing members. Now initialization calls a StackOverflowException.
So my question is: why is the expression even compiling? What should he do? I feel like I should be missing out on something really obvious.