In C#3.0, a collection initializer specifies the elements of a collection. A collection initializer is made up of the following way,.Add(T) method for each specified element in order. All the initialization values are of type string. Otherwise, you'd get a compiler error.
Example:
Suppose you want to represent a class and its enrolled Employees. You can do this through collection initializers as follows:
Run the sample given above, you get the following result.
Hope this helps!!! Share your thoughts with me !!!
- Rangoli
- A sequence of object initializers, enclosed by "{" and "}" tokens and separated by "," .
- Element initializers, each of which specifies an element to be added to the collection object being added.
Example:
Suppose you want to represent a class and its enrolled Employees. You can do this through collection initializers as follows:
using System.Collections.Generic;
namespace VS2008New
{
public class Employee
{
public int ID { get; private set; }
public string Name { get; set; }
public string Destination { get; set; }
public int Experiance { get; set; }
public Employee(int id)
{
ID = id;
}
public override string ToString()
{
return Name + "\t" + Destination + "\t" + Experiance + "\t" + ID;
}
}
class Program
{
static void Main(string[] args)
{
List employees = CreateEmployeeList();
Console.WriteLine("Employee Lists:\n");
foreach (Employee c in employees)
Console.WriteLine(c);
}
static List CreateEmployeeList()
{
return new List
{
new Employee(1) { Name = "Tony Robert", Destination = "Saleman", Experiance = 5 },
new Employee(2) { Name = "Rangoli Kannan", Destination = "Jr Manager", Experiance = 3 },
new Employee(3) { Name = "Naren", Destination = "Sr Manager", Experiance = 7 }
};
}
}
}
Run the sample given above, you get the following result.
Hope this helps!!! Share your thoughts with me !!!
- Rangoli