ReadOnlyCollection or IEnumerable for exposing member collections?
Posted
by Erik Öjebo
on Stack Overflow
See other posts from Stack Overflow
or by Erik Öjebo
Published on 2009-01-29T12:20:04Z
Indexed on
2010/06/10
5:42 UTC
Read the original article
Hit count: 561
Is there any reason to expose an internal collection as a ReadOnlyCollection rather than an IEnumerable if the calling code only iterates over the collection?
class Bar
{
private ICollection<Foo> foos;
// Which one is to be preferred?
public IEnumerable<Foo> Foos { ... }
public ReadOnlyCollection<Foo> Foos { ... }
}
// Calling code:
foreach (var f in bar.Foos)
DoSomething(f);
As I see it IEnumerable is a subset of the interface of ReadOnlyCollection and it does not allow the user to modify the collection. So if the IEnumberable interface is enough then that is the one to use. Is that a proper way of reasoning about it or am I missing something?
Thanks /Erik
© Stack Overflow or respective owner