7

Is it good to use such approach for keeping read-only list of string, for example, a list of fields in ADO.NET.

var list = new System.Collections.ObjectModel.ReadOnlyCollection<string>(
           new List<string>(4) { "type", "currency", "date", "amount" });

Or this is a superfluous solution?

abatishchev
  • 98,240
  • 88
  • 296
  • 433

3 Answers3

8

Depends on your position. ReadOnlyCollection works very well when you have an internal modifiable list that needs to be given to some other code that isn't allowed to change the list. For simple code, using ReadOnlyCollection is probably overkill. If the code is large and there's a risk some other programmer (or you, down the road) might accidentally attempt to modify the list, then it might be worth it.

In short: don't use ReadOnlyCollection idiomatically, use it when it makes sense.

John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
6

If possible, prefer static type checking. IEnumerable<string> is readonly.

IEnumerable<string> list = new List<string> { "type", "currency", "date", "amount" };

Subsequent code can't modify the list, and mistakes will be caught at compile time - unless you use reflection, but then reflection could be used to circumvent runtime checks as well.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • No, don't use this as subsequent code can simply cast back to `List`; reflection is not required. – Kevin Brock Jul 29 '12 at 22:17
  • 1
    @KevinBrock Even if reflection were required, it would be zero-effort to get around, see: http://stackoverflow.com/a/1232332/27423 - trying to "block" unwrapping of your "readonly" wrapper is worse than useless. It adds complexity (and maybe runtime cost) without adding any actual value. Document the correct usage of your API through the static type system - anything else is pointless. – Daniel Earwicker Jul 30 '12 at 08:20
4

Going back to .NET 2.0, the List class had a AsReadOnly() method. When generics came along, the List<T> got it too. Here's the MSDN reference page.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Thought
  • 700
  • 2
  • 9
  • 21