views:

257

answers:

2

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?

+3  A: 

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
+3  A: 

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