Michael Todd
Michael Todd

Reputation: 17051

Prevent other classes from altering a list in a class

If I have a class that contains, for example, a List<string> and I want other classes to be able to see the list but not set it, I can declare

public class SomeClass()
{
    public List<string> SomeList { get; }
}

This will allow another class to access SomeList and not set it.

However, although the calling class can't set the list, it can add or remove elements. How do I prevent that? I guess I could use a field and return a copy of the List instead of using a property, but that just doesn't feel right.

(This should be very simple but I must be missing something....)

Upvotes: 14

Views: 5953

Answers (4)

Jay
Jay

Reputation: 57919

Return IEnumerable<string>, which is immutable. The getter should look like this:

public IEnumerable<string> SomeList
{
   get
   {
      foreach(string s in someList) yield return s; // excuse my inline style here, zealots
      yield break;
   }
}

Upvotes: 2

Russ Cam
Russ Cam

Reputation: 125488

public class SomeClass()
{
    private List<string> _someList = new List<string>();

    public IList<string> SomeList 
    { 
         get { return _someList.AsReadOnly(); } 
    }
}

Upvotes: 0

Anon.
Anon.

Reputation: 59973

You won't be able to use an autoproperty.

public class SomeClass()
{
    private List<string> someList;
    public IList<string> SomeList { 
        get { return someList.AsReadOnly(); }
    }
}

Upvotes: 16

Gavin Miller
Gavin Miller

Reputation: 43815

You'll want to return the list as a ReadOnly list. You can do this with the following code:

using System.Collections.ObjectModel;

public ReadOnlyCollection<string> GetList() {
    return SomeList.AsReadOnly();
}

Upvotes: 5

Related Questions