Object Initializer and Collection Initializer in C#
Object Initializer and Collection Initializer in C#
Object Initializer -
Object Initializer is a way to assign values at the time of object creation. It does not require constructor call to assign fields values. The syntax involves wrapping object initializer in braces and values being separated by commas.
Let’s see an example –
using System;
namespace ObjectInitializer
{
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)
{
Employee employee = new Employee { ID=277980, Name="Meena", Email="meena@microsoft.com" };
Console.WriteLine(employee.ID);
Console.WriteLine(employee.Name);
Console.WriteLine(employee.Email);
}
}
}
Output –
277980
Meena
Collection Initializer –
Collection Initializer is used to initialize a collection type that implements IEnumerable interface.
Let’s see an example –
using System;
using System.Collections.Generic;
namespace CollectionInitializer
{
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class CollectionInitializer
{
public static void Main(string[] args)
{
List employees = new List< Employee > {
new Employee { ID=277980, Name="Meena", Email="meena@microsoft.com" },
new Employee { ID=277981, Name="Donmic", Email="donmic@microsoft.com" },
new Employee { ID=277982, Name="Vikram", Email="vikram@microsoft.com" }
};
foreach (Employee employee in employees)
{
Console.Write(employee.ID+" ");
Console.Write(employee.Name+" ");
Console.Write(employee.Email+" ");
Console.WriteLine();
}
}
}
}
Output –
277980 Meena meena@microsoft.com
277981 Donmic donmic@microsoft.com
277982 Vikram vikram@microsoft.com
