Say I have:
class foo
{
private List<T> bar;
public IEnumerable<T> GetBar();
}
where GetBar() should return that very same List, without exposing internals (i.e. no other class should be able to remove elements from the internal list, reorder it etc.) and avoiding excessive copying. What is the standard way to do this?
If you want to return an immutable list, return bar.AsReadOnly().
Typically the member that exposes this readonly wrapper would be of type IList<T>. I would only downcast to IEnumerable<T> if I wanted to indicate to the consumer that the implementation might use lazy enumeration.
Personally I'd make it a property, and return the same readonly wrapper on each invocation:
class Foo
{
private List<T> bar;
private IList<T> readonlyBar;
public Foo()
{
bar = ...;
readonlyBar = bar.AsReadOnly();
}
public IList<T> Bar
{
get { return readonlyBar; }
}
}
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