I have a C# console app. My app has a class called Item. Item is defined like this:
public class Item {
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
I want to build a List<Item> items
; In my head, C# had a shorthand way of defining a list at runtime. Something like:
List<Item> items = new List()
.Add(new Item({ Id=1, Name="Ball", Description="Hello" })
.Add(new Item({ Id=2, Name="Hat", Description="Test" });
Now I can't seem to find a short-hand syntax like I'm mentioning. Am I dreaming? Or is there a short-hand way to build a list of collections?
Thanks!
You can use an object & collection initializer
(C# 3.0 and above) like this:
List<Item> items = new List<Item>
{
new Item { Id=1, Name="Ball", Description="Hello" },
new Item { Id=2, Name="Hat", Description="Test" }
};
It has. The syntax would be like this:
List<Item> items = new List<Item>()
{
new Item{ Id=1, Name="Ball", Description="Hello" },
new Item{ Id=2, Name="Hat", Description="Test" }
}
I would do just like this:
var items = new List<Item>
{
new Item { Id=1, Name="Ball", Description="Hello" },
new Item { Id=2, Name="Hat", Description="Test" }
};
Here are the details.
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