I have,
List<Items> itemDetails = new List<Item>();
itemDetails.Add(new Item { isNew = true, Description = "test description" });
Why i can't write above code like
List<Items> itemDetails = new List<Item>().Add(new Item { isNew = true, Description = "test description" });
It gives error
Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<>
When you call Add
, that has a void
return type... which is why you're getting the error. The overall result of the expression new List<Item>().Add(...)
is void
.
However, you can use a collection initializer:
List<Item> itemDetails = new List<Item>
{
new Item { isNew = true, Description = "test description" },
new Item { isNew = false, Description = "other description" }
};
That's basically telling the compiler to convert each element within the collection initializer into an Add
call for you.
See more on this question at Stackoverflow