Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadOnlyCollection IEnumerable

Tags:

c#

.net

linq

string[] _myStrings = { "Hello", "There", "Happy", "Day" };

public IEnumerable<string> MyStrings1
{
    get
    {
        return new System.Collections.ObjectModel.ReadOnlyCollection<string>(_myStrings);
    }
}

public IEnumerable<string> MyStrings2
{
    get
    {
        return from s in _myStrings select s;
    }
}

I have seen some discussion about not using arrays for public properties. I have been using the MyStrings2 Convention. Is there some reason I should be using MyStrings1 instead?

like image 892
pufferfish Avatar asked Dec 31 '12 17:12

pufferfish


1 Answers

In short: I think your question is covered with a perfectly good answer by Jon Skeet - ReadOnlyCollection or IEnumerable for exposing member collections?

In addition: You can just emulate AsReadOnly():

public ReadOnlyCollection<Abc> List
{
    get { return new ReadOnlyCollection(list); }
}

UPDATE:
This doesn't create a copy of list. ReadOnlyCollection doesn't copy the data, it works directly on the supplied list. See documentation:

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

This constructor is an O(1) operation.

like image 172
Yusubov Avatar answered Sep 28 '22 20:09

Yusubov