Collection Initializer in .Net Framework 3.0 onwards. Collection initializer gives a simple syntax to create instance of a collection.
- Collection initializer is new feature of C# 3.0.
- Collection initializer gives a simple syntax to create instance of a collection.
- Any object that is implementing System.Collections.Generic.ICollection<T>can be initialized with collection initializer.
Student.cs
1 | public class Student |
2 | { |
3 | public string FirstName { get ; set ; } |
4 | public string LastName { get ; set ; } |
5 | } |
Now if we want to make collection of this class and add items of type student in that collection and retrieve through the collection, we need to write below code
Program.cs
01 | using System; |
02 | using System.Collections.Generic; |
03 | using System.Linq; |
04 | using System.Text; |
05 | namespace ConsoleApplication16 |
06 | { |
07 | class Program |
08 | { |
09 | static void Main( string [] args) |
10 | { |
11 | List<Student> lstStudent = newList<Student>(); |
12 | Student std = newStudent(); |
13 | std.FirstName = "Dhananjay" ; |
14 | std.LastName = "Kumar " ; |
15 | lstStudent.Add(std); |
16 | std = newStudent(); |
17 | std.FirstName = "Mritunjay " ; |
18 | std.LastName = "Kumar" ; |
19 | lstStudent.Add(std); |
20 | foreach (Student resstd in lstStudent) |
21 | { |
22 | Console.WriteLine(resstd.FirstName); |
23 | } |
24 | Console.Read(); |
25 | } |
26 |
27 | } |
28 | } |
Output
In above code,
- An instance of List of Student is getting created.
- An instance of the Student is getting created.
- Using the Add method on the list, instance of being added to list of students.
- Using For each statement iterating through the list to get the values.
If we see the above syntax
- It is highly readable.
- It is single statement.
- Instance of Student class is getting added on the fly.
In retrieving implicit type local variable is being used to fetch the different instance of the student in list of student
01 | List<Student> lstStudent = newList<Student>() |
02 | { |
03 | newStudent{FirstName = "Dhananjay" ,LastName= "Kumar" }, |
04 | newStudent {FirstName = "Mritunjay" , LastName = "Kumar" } |
05 | }; |
06 | foreach (var r in lstStudent) |
07 | { |
08 | Console.WriteLine(r.FirstName); |
09 | } |
10 | Console.Read(); |
Output
How it internally works?
A collection initializer invokes the ICollection<T>.Add(T) method for each specified element in order. In the above example , it will call
ICollection<Student>.Add(instance of Student )
No comments:
Post a Comment