Why is there no constructor for List <T> that takes params?

I know that I can use a collection initializer to initialize a list:

var list = new List<string> { "test string 1", "test string 2" }; 

If I remember, this internally calls Add for each element.

Why is there no constructor for List<T> that accepts params T[] items ?

 var list = new List<string>("test string 1", "test string 2"); 
+6
source share
3 answers

The real reason is that the designers simply did not feel that the benefits of this small amount of syntactic sugar were worth it to realize or that it could cause some confusion.

There is a small problem if you want to create a List<int> . What does it mean?

 var list = new List<int>(10); 

Is it a new list with a capacity of 10 or a new list containing one item, 10?

Spoiler if you don’t know how the compiler interprets it:

It will be considered as capacity. If T is something other than int , it will be considered as one element. It will also be considered as a separate element if you specify the parameter name - List<int>(items:10)

In any case, there is no reason why you could not just write:

 var list = new List<string>(new[] { "test string 1", "test string 2" }); 

This is exactly what the compiler would do if there was a constructor by supplying the params argument, and it really is a little more efficient than a collection initializer. To type a few extra characters to accomplish this, this is actually not a big deal in the grand scheme of things.

+17
source

... because there is no convincing case for its creation? In particular, there is no way to know that params used as params , and not just by passing string[] in, so it will not be able to trust this array as a backup array, so it will be an additional and unnecessary distribution of the vector. And the collection initializer syntax works very nicely. If you want it to be allocated in the correct size, you can always use:

 var list = new List<string>(2) { "test string 1", "test string 2" }; 

although, frankly, the number of times this was important is really small.

In fact, I spend a lot of time removing params . On a busy site, this is noticeably painful (when used in hot code).

+8
source

Because no one has implemented it.

Also, this is not necessary due to the collection initializer syntax, which is roughly equivalent (see @pswg answer)

But! Wait ... I feel so generous, so I consider this gift from me to you:

 public class SpecialListJustForYou<T> : List<T> { public SpecialListJustForYou(int capacity):base(capacity){} public SpecialListJustForYou(IEnumerable<T> collection):base(collection){} public SpecialListJustForYou():base(){} // and here the magic! public SpecialListJustForYou(params T[] items) : base(items == null ? Enumerable.Empty<T>() : items.AsEnumerable()){} } 
+3
source

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


All Articles