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!

+7
source share
6 answers

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; 
+19
source

This is because the children property is not initialized.

 MyNode newNode = new MyNode { NodeName = "newNode", Children = new List<T> (/*smth*/) }; 
+4
source

Since you are executing a method without assigning a value

+2
source

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 } }; 
+2
source

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).

+2
source

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.

+2
source

All Articles