As I generally only return immutable (unmodifiable) objects from properties/methods, this answer assumes you want to do the same.
Don't forget about ReadOnlyCollection<T>
which returns an immutable collection that can still be accessed by index.
If you're using IEnumerable<T>
and releasing your type into the uncontrollable wilderness, be wary of this:
class MyClass {
private List<int> _list;
public IEnumerable<int> Numbers {
get { return _list; }
}
}
As a user could do this and mess up the internal state of your class:
var list = (List<int>)myClass.Numbers;
list.Add(123);
This would violate the read-only intention for the property. In such cases, your getter should look like this:
public IEnumerable<int> Numbers {
get { return new ReadOnlyCollection<int>(_list); }
}
Alternatively you could call _list.ToReadOnly()
. I wrote it out in full to show the type.
That will stop anyone modifying your state (unless they use reflection, but that's really hard to stop unless you build immutable collections like those use in many functional programming languages, and that's a whole other story).
If you're returning read only collections, you're better off declaring the member as ReadOnlyCollection<T>
as then certain actions perform faster (getting count, accessing items by index, copying to another collection).
Personally I'd like to see the framework include and use an interface like this:
public interface IReadOnlyCollection<T> : IEnumerable<T>
{
T this[int index] { get; }
int Count { get; }
bool Contains(T item);
void CopyTo(T[] array, int arrayIndex);
int IndexOf(T item);
}
You can get all these functions using extension methods on top of IEnumerable<T>
but they're not as performant.