Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a non-mutable IEnumerable<>?

Tags:

c#

.net

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, it is ok if instances of Bar are modified.
I simply want to make sure the collection itself is not modified.

I'm sure I read an answer somewhere on SO where someone pointed this was possible, but for the life of me, I can't find it again.

like image 236
Benoit Avatar asked Sep 18 '25 17:09

Benoit


1 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(); }
}
like image 51
Noldorin Avatar answered Sep 21 '25 06:09

Noldorin