String[]
is light weight compared to list<string>
. So if I don't have any need to manipulate my collection, should I use string[]
or is it always advisable to go for list<string>
?
In case of list<string>
, do we need to perform null check or not required?
Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.
In general, it's better to use lists in C# because lists are far more easily sorted, searched through, and manipulated in C# than arrays. That's because of all of the built-in list functionalities in the language.
List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists.
A list is an abstract data type; that is to say, it is any data structure that supports a specific bunch of operations. An array is a collection of homogeneous parts. A list is a collection of heterogeneous elements.
Use string[]
when you need to work with static arrays: you don't need to add and remove elements -> only access elements by index. If you need to modify the collection use List<string>
. And if you intend to only loop through the contents and never access by index use IEnumerable<string>
.
If the collection should not be modified, use string[] or even better, IEnumerable<string>
. This indicates that the collection of strings should be treated as a read-only collection of strings.
Using IEnumerable<string>
in your API also opens up for the underlying implementation to be changed without breaking client code. You can easily use a string array as the underlying implementation and expose it as IEnumerable<string>
. If the implementation at a later stage is better suited using a list or other structure, you can change it as long as it supports IEnumerable<string>
.
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