Collection Initializer in C#

Collection initializer gives a simple syntax to create instance of a collection such as List collection.

Suppose that, we want to make collection of Employee class and add items of type employee in that collection, then we need to write below code. In the given code, we have created the hard coded list of employee, but in real life example you can access this list from the database.

Example

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Employee()
        {
            this.Name = "N/A";
            this.ID = 0;
        }       
       
        public static List<Employee> GetEmployees()
        {
            List<Employee> list = new List<Employee>()
            {
                new Employee(){ID=1,Name="Raj"},
                new Employee(){ID=2,Name="Digvijay"},
                new Employee(){ID=3,Name="Ramya"},
                new Employee(){ID=4,Name="Ramesh"}
            };            
            return list;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee obj = new Employee();
            foreach (Employee emp in Employee.GetEmployees())
            {
                Console.WriteLine("Employee ID ={0} , Employee Name ={1}", emp.ID, emp.Name);
            }
            Console.ReadLine();
        }
    }
}

Implicit typing of local variables

You can use var keyword for local variable in place of type (built-in type, an anonymous type, a user-defined type). If you declare a var type variable, then compiler infer the type of the variable from the expression on the right side of the initialization statement. It enables you to perform implicit typing.

Key things about var:

  • var can be used with a local variable only.
  • It should be initialized at time of declaration.
  • Var type cannot be declared as static.
  • Var type cannot be null.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
Example:

Local VariableCompiler will infer as:
var i = 10;Int i=10;
var s = "Hello World";String s=”Hello World”;
var num = new int[ ] {10, 20, 30};Int [ ] num = new int [ ] {10, 20, 30};
var d = new Dictionary();Dictionary d = new Dictionary();

Note: Please refer the previous example for below code.

var result =
                from c in Employee.GetEmployees()
                where c.ID == 1
                select c;
            foreach (var emp in result)
            {
                Console.WriteLine ("Employee ID = {0} , Employee Name ={1}", emp.ID,
     emp.Name);
            }


When you use the above code you will get the employee ID and name whose ID is 1.
We will understand from, where and select clause, when discuss the LINQ.