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>() { };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With