Collection Initializers with Parameter Arrays

suggest change

You 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 }
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents