Collection Initializers with Parameter Arrays
suggest changeYou can mix normal parameters and parameter arrays:
public class LotteryTickets : IEnumerable
{
private readonly List<LotteryTicket> tickets = new List<LotteryTicket>();
public void Add(string userName, params int[] luckyNumbers)
{
tickets.Add(new LotteryTicket
{
UserName = userName,
LuckyNumbers = luckyNumbers
});
}
public IEnumerator GetEnumerator() => tickets.GetEnumerator();
}
public class LotteryTicket
{
public int[] LuckyNumbers;
public string UserName;
}
Each brace group is one Add call on that collection. List<LotteryTicket> does not have an Add(string, params int[]) method, so the initializer has to target the type that defines it:
var tickets = new LotteryTickets
{
{ "Mr Cool", 35663, 35732, 12312, 75685 },
{ "Bruce", 26874, 66677, 24546, 36483, 46768, 24632, 24527 },
{ "John Cena", 25446, 83356, 65536, 23783, 24567, 89337 }
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents