haydnD
haydnD

Reputation: 2293

why can't you use List<string> instead of string[] when using Directory.GetDirectories("c:\\")?

I'm just curious as to why I have to use the string[] when using Directory.GetDirectories()

string[] directories = Directory.GetDirectories("c:\\");

foreach (var dir in directories)
{
     Console.WriteLine(dir);
}

Why can't I use

List<string> _directories = new List<string>();
        _directories = Directory.GetDirectories("c:\\");

Upvotes: 0

Views: 251

Answers (5)

Dave Bish
Dave Bish

Reputation: 19646

You should use Directory.EnumerateDirectories() Anyway - as it will only enumerate the directories, instead of filling up a whole array - which will use less memory.

from MSDN:

The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

(unless you really need a filled array)

EDIT:

So - to answer the question more specifically - if you wish to return a List<> type, you're better-off doing:

var dirs = Directory.EnumerateDirectories("c:\\").ToList();

As this will avoid the 'array' step of the conversion.

Upvotes: 5

Blindy
Blindy

Reputation: 67380

The short answer is performance. If you know how many items you'll have beforehand (and you do for searches), you can preallocate a normal array and fill it in, without the double growth strategy penalty List<> uses.

Once you have your basic string[] object, you can easily feed it to a list and append to it if you really need to. Going the other way would incur a performance penalty for the most often used use cases.

Upvotes: 0

Grokodile
Grokodile

Reputation: 3933

Directory.GetDirectories has been around since .Net 1.1 before generics such as List<T> were introduced.

Upvotes: 3

Razer
Razer

Reputation: 93

Because its the return type of the method obviously.

Upvotes: 0

Roger Lipscombe
Roger Lipscombe

Reputation: 91845

Because GetDirectories returns a string[], basically.

Anyway, you can:

List<string> _directories = new List<string>(Directory.GetDirectories("c:\\"));

...or:

List<string> _directories = Directory.GetDirectories("c:\\").ToList();

Upvotes: 10

Related Questions