8
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?

Yusubov
  • 5,815
  • 9
  • 32
  • 69
pufferfish
  • 291
  • 4
  • 12
  • possible duplicate of [ReadOnlyCollection or IEnumerable for exposing member collections?](http://stackoverflow.com/questions/491375/readonlycollection-or-ienumerable-for-exposing-member-collections) – nawfal Nov 11 '13 at 11:00

2 Answers2

14

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.

Community
  • 1
  • 1
Yusubov
  • 5,815
  • 9
  • 32
  • 69
1

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009