Object and Collection Initializer in C#

An object and collection initializer is a fascinating and extremely useful feature of the C# programming language. This feature provides an alternative method for initialising a class or collection object. The main benefits of using these are that they make your code more readable, they provide an easy way to add elements to collections, and they are commonly used in multi-threading.

Object Initializer 

Object Initializer is a new way to assign values to objects when they are created. It is not necessary to use a constructor call to assign values to fields. The object initializer is surrounded by braces, and the values are separated by commas.

Example

using System;  
namespace CSharpFeatures  
{  
    class Employee  
    {  
        public int ID { get; set; }  
        public string Name { get; set; }  
        public string Email { get; set; }  
    }  
    class ObjectInitializer  
    {  
        public static void Main(string[] args)  
        {  
            // Using Object Initialilzer  
            Employee  employee = new Employee   { ID=25, Name="Niki", Email="niki@gmail.com" };  
            // Displaying Initialized Values  
            Console.WriteLine(employee.ID);  
            Console.WriteLine(employee.Name);  
            Console.WriteLine(employee.Email);  
        }  
    }  
}

OUTPUT

25
Niki
niki@gmail.com

Collection Initializer

Collection Initializer allows us to set up a collection type that conforms to the IEnumerable interface. The collection initializer is demonstrated in the following example.

Example

using System;  
using System.Collections.Generic;  
namespace CSharpFeatures  
{  
    class Employee
    {  
        public int ID { get; set; }  
        public string Name { get; set; }  
        public string Email { get; set; }  
    }  
    class ObjectInitializer  
    {  
        public static void Main(string[] args)  
        {  
            List<Employee> employee= new List<Employee> {  
                new Employee { ID=25, Name="Niki", Email="niki@gmal.com.com" },  
                new Employee { ID=26, Name="Ruju", Email="ruju@gmail.com" },  
                new Employee { ID=27, Name="Damini", Email="damini@gmail.com" }  
            };  
            foreach (Employee emp in employee)  
            {  
                Console.Write(emp.ID+" ");  
                Console.Write(emp.Name+" ");  
                Console.Write(emp.Email+" ");  
                Console.WriteLine();  
            }  
        }  
    }  
}

OUTPUT

25 Niki niki@gmail.com
26 Ruju ruju@gmail.com
27 Damini damini@gmail.com

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories