I have "best practices" question about OOP in C# (but it sort-of applies to all languages).
Consider having library class with object that is to be exposed to public, say via property accessor, but we do not want the public (people using this library class) to change it.
class A
{
// Note: List is just example, I am interested in objects in general.
private List<string> _items = new List<string>() { "hello" }
public List<string> Items
{
get
{
// Option A (not read-only), can be modified from outside:
return _items;
// Option B (sort-of read-only):
return new List<string>( _items );
// Option C, must change return type to ReadOnlyCollection<string>
return new ReadOnlyCollection<string>( _items );
}
}
}
Obviously the best approach is "option C", but very few objects have ReadOnly variant (and certainly no user-defined classes have it).
If you were the user of class A, would you expect changes to
List<string> someList = ( new A() ).Items;
propagate to original (A) object? Or is it okay to return a clone provided that it was written so in comments/documentation? I think that this clone approach might lead to quite difficult-to-track bugs.
I remember that in C++ we could return const objects and you could only call methods marked as const on it. I guess there is no such feature/pattern in the C#? If not why would they not include it? I believe it is called const correctness.
But then again my main question is about "what would you expect" or how to handle Option A vs B.