Simon
Simon

Reputation: 8357

If I have a List<T>, is there any advantage of using an IEnumerable<T> when looping through the list?

In C#, if I have a List<T>, that is stored in an object, and I want to check if a value exists in the list, is there any advantage of calling a function that returns an IEnumerable<T> rather than looping through the List<T> that I already have?

Thanks.

Upvotes: 0

Views: 59

Answers (3)

jdphenix
jdphenix

Reputation: 15415

You have a read operation that you're describing. Return your IList<T> as an IEnumerable<T>.

Then, use linq's Contains() - which internally check for implementation of ICollection and optimize to the use the implementation available, despite that fact that it accepts an IEnumerable<T>. In other words, you lose nothing by returning an IEnumerable<T>.

Upvotes: 0

Sean
Sean

Reputation: 3042

when you return the property as IEnumerable<T>, that tells the caller that you can not mutate the value of it, you can just iterator it, that can help you get rid of lots of unexpected error.

if you expose the property as List<T>, it can be easily mutated by "others", this can cause a mess in a large system, so keep your data as immutatable as possible.

image you are tracking a bug because the item in the list is not currect, if the property is exposed as List, you have to look into all the usage of that property to see who changed it, but if you you exposed it as Iemumerable, you can be sure that the only place to change it is the object it self, that will save you a lot of time to tracking the bug.

Upvotes: 1

Muhammad Nasir
Muhammad Nasir

Reputation: 2204

List is a mutable collection - you can add to, remove from and sort it etc. It is flexible but IEnumerable allows you to use the same code to work with any implementation of arrays, linked lists, lists, iterators returned from methods using yield statements.

Upvotes: 0

Related Questions