TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Initialize List

Initialize generic Lists in various ways. Use collection initializer expressions.
List, initialize. A List can be initialized in many ways. Each element can be added in a loop with the Add method. A special initializer syntax form can be used.List
With this initializer syntax, objects inside the List can be initialized. Most syntax forms are compiled to the same intermediate representation. There is no performance difference.
First example. The C# language has many ways to populate a List with values. Many of them are compiled into the same code. We use curly brackets and add elements in expressions.

Part 1: These first 2 declarations specify 3 strings to be added to a new List.

Part 2: Here the code copies an external array to the internal buffer of the List at runtime. This avoids unnecessary resizing.

Part 3: This code is an unclear way of initializing a List variable in the normal case. But it works.

Part 4: We can avoid a List initializer, and just create an empty list and Add() elements to it.

C# program that initializes string list using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: use collection initializer. // ... Use it with var keyword. List<string> list1 = new List<string>() { "carrot", "fox", "explorer" }; var list2 = new List<string>() { "carrot", "fox", "explorer" }; // Part 2: use new array as parameter. string[] array = { "carrot", "fox", "explorer" }; List<string> list3 = new List<string>(array); // Part 3: use capacity in constructor and assign. List<string> list4 = new List<string>(3); list4.Add(null); // Add empty references (BAD). list4.Add(null); list4.Add(null); list4[0] = "carrot"; // Assign those references. list4[1] = "fox"; list4[2] = "explorer"; // Part 4: use Add method for each element. List<string> list5 = new List<string>(); list5.Add("carrot"); list5.Add("fox"); list5.Add("explorer"); // Make sure they all have the same number of elements. Console.WriteLine(list1.Count); Console.WriteLine(list2.Count); Console.WriteLine(list3.Count); Console.WriteLine(list4.Count); Console.WriteLine(list5.Count); } } Output 3 3 3 3 3
Object List. You can allocate and assign the properties of objects inline with the List initialization. Object initializers and collection initializers share similar syntax.

Object initializer: An object initializer sets the individual fields in the object such as properties.

Collection initializer: A collection initializer sets the elements in the collection, not fields.

Next: This example shows an object that has 2 properties A and B, and the properties are set in the List initializer.

Property

Note: It uses nested curly brackets. In the initialization of list1, two Test instances are allocated with the specified values.

C# program that initializes object Lists using System; using System.Collections.Generic; class Test // Used in Lists. { public int A { get; set; } public string B { get; set; } } class Program { static void Main() { // Initialize list with collection initializer. List<Test> list1 = new List<Test>() { new Test(){ A = 1, B = "Jessica" }, new Test(){ A = 2, B = "Mandy" } }; // Initialize list with new objects. List<Test> list2 = new List<Test>(); list2.Add(new Test() { A = 3, B = "Sarah" }); list2.Add(new Test() { A = 4, B = "Melanie" }); // Write number of elements in the lists. Console.WriteLine(list1.Count); Console.WriteLine(list2.Count); } } Output 2 2
Benchmark, List initializer. Let's establish that List initializers are as fast as a calling the Add method. Here we create 3-element lists with 2 syntax forms.

Version 1: This code uses the List initializer syntax to create a 3-element List of strings.

Version 2: This version of the code uses 3 Add() calls to populate an empty list. The Count is tested to ensure correctness.

Result: The 2 versions of the method take about the same amount of time to execute. We can safely create Lists with either syntax.

C# program that benchmarks List initializer using System; using System.Collections.Generic; using System.Diagnostics; class Program { const int _max = 10000000; static void Main() { // Version 1: use collection initializer. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { List<string> list = new List<string>() { "bird", "frog", "dog" }; if (list.Count != 3) { return; } } s1.Stop(); // Version 2: use Add method. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { List<string> list = new List<string>(); list.Add("bird"); list.Add("frog"); list.Add("dog"); if (list.Count != 3) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 39.93 ns Collection initializer 39.91 ns Add, Add, Add
Compiler. The C# compiler parses the initializer tokens "{" and "}" and turns them into individual Add method calls on the List. This is true for any List initializer.List Add
Definite assignment. When examining programs that use collection initializers, you will see extra temporary variables being created. At runtime, these excess opcodes are eliminated.

Note: The C# language specification states that these temporary variables are used to simplify the process of definite assignment analysis.

And: This proves initialized memory is used. See "The C# Programming Language Third Edition, Special Annotated Edition" page 266.

A review. We looked into some specifics of List initializations. We saw how to initialize string List collections using the expression-based syntax. We initialized many lists.
For development, we want to make the primary purpose of code clear. If the "addition" logic to a List is the most important part, using Add() directly might help emphasize this.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf