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