Reputation: 1983
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!
Upvotes: 12
Views: 125493
Reputation: 6971
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.
Upvotes: 4
Reputation: 6794
in my opinion, Amir popovich answer is correct and this is the way that should be...
but in case we want to declare the list same as you mentioned in the question:
List<Item> items = new List()
.Add(new Item({ Id=1, Name="Ball", Description="Hello" })
.Add(new Item({ Id=2, Name="Hat", Description="Test" });
you can write an extension method that will allow you to achieve what you want
check this code ( small console application)
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>()
.AddAlso(new Item{ Id=1, Name="Ball", Description="Hello" })
.AddAlso(new Item{ Id=2, Name="Hat", Description="Test" });
foreach(var item in items)
Console.WriteLine("Id {0} Name {1}, Description {2}",item.Id,item.Name,item.Description);
}
}
public static class Extensions
{
public static List<T> AddAlso<T>(this List<T> list,T item)
{
list.Add(item);
return list;
}
}
public class Item
{
public int Id{get;set;}
public string Name{get;set;}
public string Description{get;set;}
}
and here a working DEMO
Upvotes: 2
Reputation: 777
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" }
}
Upvotes: 20
Reputation: 29846
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" }
};
Upvotes: 34