Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use string [] vs list <string> in C#

Tags:

c#

.net

c#-4.0

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?

like image 613
Biki Avatar asked Jan 18 '11 13:01

Biki


People also ask

When should I use an array instead of a list?

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.

Which is better array or list in C#?

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.

Why do we use list in C#?

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.

What is the difference between list and array in asp net?

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.


2 Answers

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>.

like image 177
Darin Dimitrov Avatar answered Oct 11 '22 07:10

Darin Dimitrov


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>.

like image 34
Peter Lillevold Avatar answered Oct 11 '22 08:10

Peter Lillevold