Reputation: 8973
Whats the difference between these three ways of creating a new List<string>
in C#?
A = new List<string>();
B = new List<string> { };
C = new List<string>() { };
Upvotes: 5
Views: 215
Reputation: 61437
Those are equivalent, all three create an empty List<string>
.
The collection initialization syntax allows you to provide data while constructing the object,
List<string> list = new List<string> { "one", "two", "three" };
gets expanded to
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
by the compiler.
Upvotes: 4
Reputation: 22161
There is no difference because you are not initializing anything inside the list at the time of declaring it.
If you were to add some strings at declaration-time, you would need to go with the second or third choice:
var B = new List<string> { "some", "strings" };
var C = new List<string>() { "some", "strings" };
The third option would only be necessary if you were to pass a value into 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 for the List<of T>
class as well (e.g. passing an existing collection or IEnumerable into the List constructor). See MSDN for details.
Upvotes: 8
Reputation: 2720
In the example you gave to us, the result will be the same.
In terms of performance you will not find any problem using any of that options for initializing a empty list, because the IL generated will one contain the ctor(), as you can see using the IL DASM.
If you want to initialize the list with some information, you can go for the option 2 or 3.
List<string> b = new List<string> { "abc", "abc" };
List<string> c = new List<string>() { "abc", "abc"};
In terms of performance is also the same, the IL generated will be exactly the same, containing the ctor() and two Add for both.
But you should use the best one to read. To avoid any problem reading the code for you colleagues, I would go for
List<string> a = new List<string>();
But that is a question of personal opinion.
Upvotes: 1
Reputation: 150253
{}
is used for collection\object initilizer.
If it remains blank it doesn't do a thing.
So all those lines produces the same thing.
Upvotes: 1
Reputation: 9445
In your example, all three statements do the same: they create an empty string list. Statement B and C can assign some initial data to the list, e.g.
ingredients = new List<string> { "Milk", "Sugar", "Flour" };
The ()
as in statement C can omitted then.
Upvotes: 1
Reputation: 86708
Those are all identical. There's no difference in the end result, just in the syntax.
Upvotes: 4