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....)
You won't be able to use an autoproperty.
public class SomeClass()
{
private List<string> someList;
public IList<string> SomeList {
get { return someList.AsReadOnly(); }
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With