Search code examples
c#.netinitializer

Why doesn't initializer work with properties returning list<t>?


Couldn't find an answer to this question. It must be obvious, but still.

I try to use initializer in this simplified example:

    MyNode newNode = new MyNode 
    {
        NodeName = "newNode",
        Children.Add(/*smth*/) // mistake is here
    };

where Children is a property for this class, which returns a list. And here I come across a mistake, which goes like 'Invalid initializer member declarator'.

What is wrong here, and how do you initialize such properties? Thanks a lot in advance!


Solution

  • You can't call methods like that in object initializers - you can only set properties or fields, rather than call methods. However in this case you probably can still use object and collection initializer syntax:

    MyNode newNode = new MyNode
    {
        NodeName = "newNode",
        Children = { /* values */ }
    };
    

    Note that this won't try to assign a new value to Children, it will call Children.Add(...), like this:

    var tmp = new MyNode();
    tmp.NodeName = "newNode":
    tmp.Children.Add(value1);
    tmp.Children.Add(value2);
    ...
    MyNode newNode = tmp;