C # Nested initialization weirdness

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.

+4
source share
1 answer

, : ?

. # 7.6.10.2:

, , . , , , , , .

, :

Foo tmp = new Foo();
tmp.Bar.Add(1);
tmp.Bar.Add(2);
tmp.Bar.Add(3);
tmp.Baz[1].Bar.Add(4); // This will throw KeyNotFoundException if Baz is empty
tmp.Baz[1].Bar.Add(5);
tmp.Baz[1].Bar.Add(6);
Foo f = tmp;

StackOverflowException, Foo Foo, Foo ..

+7

Source: https://habr.com/ru/post/1665743/


All Articles