tags:

views:

139

answers:

5

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.

+3  A: 

You can use System.Collections.ObjectModel.ReadOnlyCollection

public ReadOnlyCollection<Bar> GetList() {return new ReadOnlyCollection<Bar>(_myList);}
Michael
carefull, you can still modify Bar instances.
eglasius
+1  A: 
return new System.Collections.ObjectModel.ReadOnlyCollection<Bar>(_myList);

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

Chris Hynes
A: 

You could expose IEnumerable from a ReadOnlyCollecton or you could do something like this (assuming LINQ):

public IEnumerable<Bar> GetList() { return (from item in _myList select item); }
Daniel Pratt
+1  A: 

You can't prevent Bar elements from being modified at the Collection level. If you only want it Not mutable regarding add/delete/etc use ReadOnlyCollection.

If you instead need to enforce that each element isn't mutable, then you have to enforce that in the Bar class i.e. don't have setters or any method that changes the state of Bar.

eglasius
+7  A: 

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(); }
}
Noldorin
+1 simple syntax :)
eglasius
@Benoit these are at the collection level, see my answer for more info about that
eglasius
Yeah, extension methods always make things nice. Note that there also exist the AsEnumerable and AsQueryable extension methods for similar circumstances.
Noldorin
(Although AsEnumerable seems might seem like a particularly useless function at first, see http://msdn.microsoft.com/en-us/library/bb335435.aspx for an explanation.)
Noldorin