Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a List of Objects in C#

Tags:

c#

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!

like image 562
xam developer Avatar asked Dec 12 '14 16:12

xam developer


3 Answers

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" }
};
like image 114
Amir Popovich Avatar answered Oct 10 '22 23:10

Amir Popovich


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" }
}
like image 14
Omni Avatar answered Oct 11 '22 00:10

Omni


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.

like image 2
nzrytmn Avatar answered Oct 11 '22 01:10

nzrytmn