Sunday, March 9, 2014

Collection Initializer


Collection Initializer

  • As  per  the  previous  examples  with  collections,  we  require  to  add  the  values  to  the collections using Add() method.
  • Suppose  you  want  to  add  so  many  elements  to  the  collection.  Then  if  you  are  using  it takes Add() method (as above), it takes no. of lines of code.
  • To solve this problem, Collection Initializer can be used.
  • Purpose: To initialize the elements of a collection, at the time declaration.
  • Syntax:

List collection class: List<data type> obj = new List<data type>() { val1, val2, …. };
ArrayList” collection class: ArrayList obj = new ArayList() { val1, val2, …. };

Program of Collection Initializer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CollectionInitializerDemo
{
class Program
 {
  static void Main(string[] args)
  {
  //Collection Initializer with List class
  Console.WriteLine("List:");
  List lst = new List() { "one", "two", "three", "four" }; //collection initializer
  lst.Add("five"); //add additional elements if required
  foreach (string s in lst)
  Console.WriteLine(s);
  Console.WriteLine("\n\nArray List:");
  ArrayList arrlst = new ArrayList() { "emp_001", "Srinivas", 8900, "Washington" }; 
  //collection initializer
  arrlst.Add(DateTime.Now); //add additional elements if required
  foreach (object s in arrlst)
  Console.WriteLine(s);
  Console.Read();
 }
}
}