The Add method adds an element to a List. The code snippet in Listing 2 creates two List<T> objects and adds integer and string items to them respectively.
Example 1: Adding elements into List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Dynamic ArrayList with no size limit List<int> numberList = new List<int>(); numberList.Add(32); numberList.Add(21); numberList.Add(45); numberList.Add(11); numberList.Add(89); // List of string List<string> authors = new List<string>(5); authors.Add("Mahesh Chand"); authors.Add("Chris Love"); authors.Add("Allen O'neill"); authors.Add("Naveen Sharma"); authors.Add("Monica Rathbun"); authors.Add("David McCarter"); |
Example 2: Adding elements into List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
static void Main() { // Version 1: create a List of ints. // ... Add 4 ints to it. var numbers = new List<int>(); numbers.Add(2); numbers.Add(3); numbers.Add(5); numbers.Add(7); Console.WriteLine("LIST 1: " + numbers.Count); // Version 2: create a List with an initializer. var numbers2 = new List<int>() { 2, 3, 5, 7 }; Console.WriteLine("LIST 2: " + numbers2.Count); } |