views:

186

answers:

2

Let's say I have a C# class:

class Foo
{
    private List<Bar> _barList;
    List<Bar> GetBarList() { return _barList; }
...
}

A client can call it:

var barList = foo.GetBarList();
barList.Add( ... );

Is there a way to make the Add method fail because only a read-only version of _barList is returned?

+10  A: 

Yes, in GetBarList() return _barList.AsReadOnly().

Edit:
As Michael pointed out below, your method would have to return an IList<Bar>.

Jay Riggs
Nice! Note that, since this returns a ReadOnlyCollection, which implements IList, your accessor must also return an IList, and not a List.
Michael Petrotta
awesome, thanks!
zumalifeguard
Michael, thanks for pointing that out.
Jay Riggs
+4  A: 

You may try to use ReadOnlyCollection. Or return just IEnumerable from your method, clients will not have methods to modify it.

elder_george