ā Difference between `string[]` and `IEnumerable<string>`
in the following the code, the output seems to be the same:
i know that
enum
s are used to define a set of exhaustive types, and are closely related to int
s.
but what does it mean to have IEnumerable<string>
and how different is it from string[]
?9 Replies
GetDirectories
returns a complete collection. all items have been evaluated and transformed.
EnumerateDirectionaries
yields every result back to you one by one. you can use it if you don't want to go over every single result; for example when you're looking for just one specific directory. when you break
in the loop over EnumerateDirectories
, it won't continue searching for the next result.
EnumerateDirectories
is an iterator methodero
REPL Result: Success
Console Output
Compile: 577.671ms | Execution: 99.265ms | React with ā to remove this embed.
it's a bit confusing if you don't know what's going on
what i have gathered from this is that there's a difference in the iteration:
EnumerateDirectories
will iterate over the directories one by one to match a condition's expression, whereas GetDirectories
will iterate over all the files/directories first, provide a string[]
over which we iterateYes so essentially
EnumerateDirectories
doesn't do anything until you call ToArray
/ToList
, at which it will start to actually perform the logic and enumerate
Meaning that you can do this multiple times and it will return the current state. This is often a pitfall for developers using IEnumerable
because they do not realize that they enumerate multiple times
It's a very generic way to enumerate something because it simply specifies a method to get the current item and to go to the next one, so you can wrap it in many things
in .NET most collection types implement IEnumerable
for this so you can foreach
the collections
So in the end it's sort of the same
It's a complex topicwhat does it mean when you say current state here?
See https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1?view=net-8.0
The only thing it does is implement
GetEnumerator
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1.getenumerator?view=net-8.0#system-collections-generic-ienumerable-1-getenumerator
So collections implement this and have this methodokay
š
This returns
IEnumerator
, which is something else https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerator-1?view=net-8.0
And this is something that collections or things implement to returns their current state.
So for example, arrays and lists just return the current index, and they will have an integer for their current position, or state
Managed by Current
, MoveNext()
and there's also Reset()
to reset iterating
So when you call ToArray
for example it uses these methods to create an array from your IEnumerable