Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between these three ways of creating a new List<string> in C#?

Tags:

c#

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>() { };
like image 690
Eric Yin Avatar asked Jan 01 '12 21:01

Eric Yin


1 Answers

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.

like image 136
Jason Down Avatar answered Oct 21 '22 04:10

Jason Down