Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard way of returning an internal collection as IEnumerable<T>

Tags:

c#

ienumerable

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?

like image 580
J Fabian Meier Avatar asked Jan 28 '26 02:01

J Fabian Meier


1 Answers

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; }
    }
}
like image 132
Joe Avatar answered Jan 29 '26 15:01

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!