In C#, can a method return List such that clients can only read it, but not write to it?
Let's say I have a C# class:
class Foo
{
private List<Bar> _barList;
List<Bar> GetBarList() { return _barList开发者_Go百科; }
...
}
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?
Yes, in GetBarList()
return _barList.AsReadOnly()
.
Edit:
As Michael pointed out below, your method would have to return an IList<Bar>
.
You may try to use ReadOnlyCollection. Or return just IEnumerable from your method, clients will not have methods to modify it.
精彩评论