How to prevent the calling method from modifying the returned collection?

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).

+3
4

, , . / , .

, ReadOnlyCollection<T> . , .

- ...

  • IEnumerable<T>, , .
+5

? [ , ]

0

AsReadOnly:

public IEnumerable<Foo> GetFoos()
{
    return Array.AsReadOnly(this.foos);
    // or if it is a List<T>
    // return this.foos.AsReadOnly();
}
0

In such cases, I create insde class methods to access individual elements of a private collection. You can also implement indexer ( http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx ) in a class that contains a private collection.

0
source

Source: https://habr.com/ru/post/1714161/


All Articles