Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent other classes from altering a list in a class

Tags:

c#

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....)

like image 689
Michael Todd Avatar asked Jan 28 '10 21:01

Michael Todd


2 Answers

You won't be able to use an autoproperty.

public class SomeClass()
{
    private List<string> someList;
    public IList<string> SomeList { 
        get { return someList.AsReadOnly(); }
    }
}
like image 186
Anon. Avatar answered Oct 18 '22 20:10

Anon.


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();
}
like image 29
Gavin Miller Avatar answered Oct 18 '22 20:10

Gavin Miller