insomniac
insomniac

Reputation: 325

How to cast DirectoryInfo.EnumerateDirectories to List<DirectoryInfo>

This question is related to my previous post. In this instance, instead of retrieving the full names of the directories, I try to build of a variable of type List<DirectoryInfo>.

This code doesn't quite work

DirectoryInfo dirInfo = new DirectoryInfo(path);
List<DirectoryInfo> dirList = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories);          

throws an error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'

And this version:

List<DirectoryInfo> dirList = dirInfo.EnumerateDirectories<DirectoryInfo>("*.", SearchOption.AllDirectories);     

throws this error:

The non-generic method 'DirectoryInfo.EnumerateDirectories()' cannot be used with type arguments.

Any suggestions or tips would be appreciated.

Upvotes: 0

Views: 368

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 416179

EnumerateDirectories() returns IEnumerable<DirectoryInfo> rather than List<DirectoryInfo>. They are different types.

You could just put a ToList() at the end:

DirectoryInfo dirInfo = new DirectoryInfo(path);
List<DirectoryInfo> dirList = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories).ToList();  

But that's the naive option. It's often not as good for performance. There's a reason IEnumerable<DirectoryInfo> was chosen instead. It has some nice advantages in terms of memory use and just-in-time/lazy operation.

So the better fix is probably replacing the type name at the beginning of the line with var:

DirectoryInfo dirInfo = new DirectoryInfo(path);
var dirList = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories);

Upvotes: 3

Selim Yildiz
Selim Yildiz

Reputation: 5380

It's because EnumerateDirectories method returns type of IEnumerable<DirectoryInfo> whereas your expected type is List<DirectoryInfo> so that you need to cast IEnumerable to List with adding ToList() as follows:

List<DirectoryInfo> dirList = dirInfo.EnumerateDirectories<DirectoryInfo>("*.", SearchOption.AllDirectories).ToList();   

Upvotes: 1

Related Questions