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!
In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.
When you assign a value to a variable when it is declared, it is called Initialization. Here is an example − int val = 50; For array initialization, you may need a new keyword, whereas to initialize a variable, you do not need it.
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
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;
It is because the children property is not initialized
MyNode newNode = new MyNode
{
NodeName = "newNode",
Children = new List<T> (/*smth*/)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With