I’m just thinking about the styling and performance. Previously I used to write something like,
var strings = new List<string> { "a", "b", "c" };
var ints = new List<int> { 1, 2, 3};
But now I tend to like this style more,
var strings = new [] { "a", "b", "c" }.ToList();
var ints = new [] { 1, 2, 3}.ToList();
I prefer the second style, but now considering – is it really worth to write it like that or maybe it’s not that efficient and requires more operations?
I disagree with Darin: they’re not equivalent in terms of performance. The latter version has to create a new array, and
ToListwill then copy it into the new list. The collection initializer version is equivalent to:Assuming the list starts off with a large enough buffer, that won’t require any further allocation – although it will involve a few method calls. If you do this for a very large number of items, then it will require more allocations than the
ToListversion, because it will copy the items as it goes.The performance difference is likely to be negligible, but it’s non-zero (and not clearly better in either direction – there are fewer calls in the array version, but more allocation).
I would concentrate more on style than performance unless you have a reason to suspect that the difference is significant, in which case you should measure rather than just guessing.
Personally I prefer the first form – I think it makes it clearer that you’re using a list right from the start. Another alternative would be to write your own static class:
Then you can write:
This still makes it clear that you’re using lists, but takes advantage of type inference.
You may well consider it overkill though 🙂