What is the difference between these three ways to create a new <string> in C #?

What is the difference between these three ways to create a new List<string> in C #?

 A = new List<string>(); B = new List<string> { }; C = new List<string>() { }; 
+6
source share
6 answers

These equivalents, all three create an empty List<string> .

  • - simple constructor without parameters
  • uses collection initialization syntax where you are allowed to skip constructor braces if the class provides a constructor without parameters
  • same as 2. just providing optional curly braces.

The collection initialization syntax allows you to provide data when building an object,

 List<string> list = new List<string> { "one", "two", "three" }; 

expands to

 List<string> list = new List<string>(); list.Add("one"); list.Add("two"); list.Add("three"); 

the compiler.

+4
source

It makes no difference because you are not initializing anything inside the list when it is declared.

If you need to add some lines during the declaration, you will need to choose the second or third option:

 var B = new List<string> { "some", "strings" }; var C = new List<string>() { "some", "strings" }; 

The third option is only needed if you must pass the value to the List<of T> constructor:

 var C = new List<string>(5) { "some", "strings" }; 

or

 var C = new List<string>(5); // empty list but capacity initialized with 5. 

There are more constructors available in the List<of T> class (for example, passing an existing collection or IEnumerable to a List constructor). See MSDN for more details.

+8
source

All this is the same. There is no difference in the end result, just the syntax.

+4
source

In your example, all three operators do the same: they create an empty list of strings. Operators B and C can assign some initial data to a list, for example.

 ingredients = new List<string> { "Milk", "Sugar", "Flour" }; 

() , as in instruction C, may be omitted.

+1
source

{} used to initialize the \ object collection.
If it remains empty, it does nothing.

Thus, all of these lines produce the same thing.

+1
source

In the example you gave us, the result will be the same.

In terms of performance, you will not find any problem using any of these parameters to initialize an empty list, because the generated IL will contain ctor (), as you can see using IL DASM.

If you want to initialize a list with some information, you can go to option 2 or 3.

 List<string> b = new List<string> { "abc", "abc" }; List<string> c = new List<string>() { "abc", "abc"}; 

In terms of performance, too, the same thing, the generated IL will be exactly the same, containing ctor () and two Adds for both.

But you must use the best to read. To avoid any trouble reading the code for your colleagues, I would go for

  List<string> a = new List<string>(); 

But this is a matter of personal opinion.

+1
source

Source: https://habr.com/ru/post/904852/


All Articles