Why does the initializer not work with properties that return the <t> list?
Could not find an answer to this question. It should be obvious, but still.
I am trying to use an initializer in this simplified example:
MyNode newNode = new MyNode { NodeName = "newNode", Children.Add(/*smth*/) // mistake is here }; where Children is a property of this class, which returns a list. And here I come across an error that looks like "Invalid initializer element declarator".
What is wrong here, and how do you initialize such properties? Thank you very much in advance!
You cannot call such methods in object initializers - you can only set properties or fields, not call methods. However, in this case, you can probably still use the object and collection initializer syntax:
MyNode newNode = new MyNode { NodeName = "newNode", Children = { /* values */ } }; Note that this will not try to assign a new value to Children , it will call Children.Add(...) , for example:
var tmp = new MyNode(); tmp.NodeName = "newNode": tmp.Children.Add(value1); tmp.Children.Add(value2); ... MyNode newNode = tmp; This is because the children property is not initialized.
MyNode newNode = new MyNode { NodeName = "newNode", Children = new List<T> (/*smth*/) }; The field initializer syntax can only be used to set fields and properties, not call methods. If Children is a List<T> , you can execute it this way by also including the list initializer syntax:
T myT = /* smth */ MyNode newNode = new MyNode { NodeName = "newNode", Children = new List<T> { myT } }; The following parameter does not set the value in the initializer:
Children.Add(/*smth*/) // mistake is here It tries to access a field element (not yet initialized).
Initializers are simply initializing properties, not other actions.
You are not trying to initialize the Children list; you are trying to add something to it.
Children = new List<smth>() initializes it.