I have methods that return personal collections to the caller, and I want the caller to not modify the returned collections.
private readonly Foo[] foos;
public IEnumerable<Foo> GetFoos()
{
return this.foos;
}
Currently, a private collection is a fixed array, but in the future the collection may become a list if it becomes necessary to add new elements at run time.
There are several solutions to prevent the caller from modifying the collection. Returning IEnumerable<T>is the easiest solution, but the caller can still update the return value to IList<T>and modify the collection.
((IList<Foo>)GetFoos())[0] = otherFoo;
Cloning collections has an obvious drawback: there are two collections that can be developed independently. So far I have considered the following options.
ReadOnlyCollection<T>.- LINQ,
Enumerable, , list.Select(item => item). Where(item => true), . - .
ReadOnlyCollection<T>, , IList<T>, Add() . , IList<T>.IsReadOnly IList<T>.IsFixedSize.
LINQ - MakeReadOnly() - , .
? ?
, ?
, . Jon Skeet "LINQ hack" , Skip(0).