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.
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(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With