user1765862
user1765862

Reputation: 14145

Adding item to List<>

Cleary I'm missing something here but I cannot see

List<Item> Items = new List<Item>().Add(new Item() { Code = "12223", ExGroup = 2});

Error message is

Cannot implicitly convert type void to List<>

Thanks

Upvotes: 3

Views: 116

Answers (5)

skjcyber
skjcyber

Reputation: 5957

If you want to do it in a single line then use Collection Initializer

such as:

List<Item> Items = new List<Item> 
     { new Item() { Code = "12223", ExGroup = 2 } };

Upvotes: 0

Raman
Raman

Reputation: 1376

You can't use Add with object initializer. List.Add return void which is not expected when you are initialising your list. Use this instead:

List<Item> Items = new List<Item>
{
   new Item { Code = "12223", ExGroup = 2 }
};

Or if you still want to use Add then you can split the code in two lines as explained by Habib.

Hope this helps.

Upvotes: 0

or like this

       List<Item> Items = new List<Item>{
             new Item() { Code = "12223", ExGroup = 2}
       };

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

Use the object initializer for a list. You can't call Add like that because it returns void, not the List itself. Try this:

List<Item> Items = new List<Item>
                   {
                       new Item { Code = "12223", ExGroup = 2 }
                   };

Upvotes: 13

Habib
Habib

Reputation: 223217

You need to do that on two lines:

List<Item> Items = new List<Item>();
Items.Add(new Item() { Code = "12223", ExGroup = 2});

The reason you are getting the error is that List<T>.Add method doesn't return anything and your Items is expected to be filled by what is returned from the right hand side.

Here is the signature for the Add method.

public void Add(
    T item
)

Upvotes: 2

Related Questions