Search code examples
c#constantsencapsulationimmutabilityreadonly

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; }
...
}

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?


Solution

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

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