Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 961
tube-builder Avatar asked Jun 17 '11 12:06

tube-builder


People also ask

How do you initialize an object in C#?

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.

What is initialization C#?

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.

How do you initialize an object?

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.


2 Answers

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;
like image 158
Jon Skeet Avatar answered Sep 30 '22 09:09

Jon Skeet


It is because the children property is not initialized

MyNode newNode = new MyNode 
    {
        NodeName = "newNode",
        Children = new List<T> (/*smth*/)
    };
like image 27
Atzoya Avatar answered Sep 30 '22 08:09

Atzoya