C# Collection Initializer Syntax


C# collections can be initialized the same way as class objects using collection initializer syntax. There is an article at Tutorials Teacher called C# – Object Initializer Syntax.

We have another post at BCN called C# Object Initializer Syntax.

using System;
using System.Collections.Generic;
namespace CollectionInitializerSyntax
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int AgeInYears { get; set; }
        public Person()  // default constructor
        {
            Id = 1;
            Name = "Sally";
            AgeInYears = 1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Person { Id = 1, Name = "John" };
            var listP = new List<Person>()
            {
                p1, 
                new Person {Id = 2, Name="Jackie"},
                new Person {Id = 3 }
            };
            foreach (var p in listP)
            {
                Console.WriteLine(p.Id + " " + p.Name + " " + p.AgeInYears);
            }
        }
    }
}

Here is the output:

1 John 1
2 Jackie 1
3 Sally 1
Press any key to continue . . .