pufferfish
pufferfish

Reputation: 291

ReadOnlyCollection IEnumerable

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?

Upvotes: 8

Views: 6801

Answers (2)

Yusubov
Yusubov

Reputation: 5843

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.

Upvotes: 14

Oded
Oded

Reputation: 499012

Exposing the array directly to those using it means that they can modify it - this is a violation of encapsulation and data hiding.

This can be a problem when your class has some invariants (guarantees about what it does and the data it holds) as it cannot make guaranteed if other classes can change its internals willy nilly.

In a multithreaded environment, this is even more of an issue, as one thread can make changes to the data while another is trying to read data - you can easily get inconsistent data in different threads.

Upvotes: 1

Related Questions