Can I have a non-mutable IEnumerable <>?

I have code similar to this:

class Foo
{
   List<Bar> _myList;
   ...
   public IEnumerable<Bar> GetList() { return _myList; }
}

The result of GetList () should NOT be mutable.

To clarify, this is normal if the Bar instances are modified.
I just want to make sure that the collection itself is not modified.

I am sure that I read the answer somewhere where someone indicated that it was possible, but for life I can no longer find me.

+3
source share
5 answers

The answers already provided will work absolutely fine, but I just thought I'd add that you can use the AsReadOnly extension method in .NET 3.5, as such:

class Foo
{
   List<Bar> _myList;
   ...
   public ReadOnlyCollection<Bar> GetList() { return _myList.AsReadOnly(); }
}
+7
source

System.Collections.ObjectModel.ReadOnlyCollection

public ReadOnlyCollection<Bar> GetList() {return new ReadOnlyCollection<Bar>(_myList);}
+3
return new System.Collections.ObjectModel.ReadOnlyCollection<Bar>(_myList);

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

+1

Bar Collection. , //etc, ReadOnlyCollection.

, , , Bar, .. , .

+1

IEnumerable ReadOnlyCollecton, - ( LINQ):

public IEnumerable<Bar> GetList() { return (from item in _myList select item); }
0

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


All Articles