collection initializer
Collection initializer is the same as object initializer it is also reduce coding time.
To use list collection we need to include system.collection.generic namespace to the program.
Example:
using System; using System.Collections.Generic; class Program { static void Main() { List<string> nameList = new List<string>() { "Sample", "Example", "Test" }; } }
We have crate list with string data type and then added list of values to the list using collection initializer.
Without collection initializer you can assign value to the list class using add method of collection.
List<string> nameList = new List<string>() nameList.Add("Sample"); nameList.Add("Example"); nameList.Add("Test");
You can also use collection list with class, structure
Let’s take an example of class using list and code initializer
List<myClass> lstObj = new List<myClass>() { new myClass(){ Id = 1, Name = "Sample" }, new myClass() { Id=2, Name = "Example" } };
Let’s take one example.
using System; using System.Collections.Generic; class Program { static void Main() { List<myClass> lstObj = new List<myClass>() { new myClass(){ Id = 1, Name = "Sample" }, new myClass() { Id=2, Name = "Example" } }; } } class myClass { public int Id { get; set; } public string Name { get; set; } }
you can also visit: www.mybook-lang.com
No comments:
Post a Comment