0

When you need to iterate over a hardcoded, ad-hoc/temporary (only used in the foreach) list of strings, what's a best practice or a better coding standard: using a List<string> or string[]? It's not an array vs List question, but a very specific code situation.

Example:

foreach (var item in new List<string>() {"A", "B", "C", ..., "Z"}) { ... }

vs

foreach (var item in new []{"A", "B", "C", ... "Z"}) { ... }
Claudiu Constantin
  • 2,138
  • 27
  • 38
  • Define "ad hoc" (*I assume that is what you meant and not "ad-host"*). Are you hard coding these strings? Are you build them from external sources? Are you changing them at a later point in time? – Igor Feb 12 '19 at 16:30
  • 1
    Best practice would be to use data structure which corresponds to your needed operations. E. g. if you need to insert/remove your data, you should use a `List`. Iteration speed for <100 items shouldn't be an important factor. – Vlad Feb 12 '19 at 16:31
  • Corrected the typo and added clarifications. The string items are only necessary in the foreach and they are hardcoded – Claudiu Constantin Feb 12 '19 at 16:32
  • 1
    Based on your updated question: You won't notice a difference either way. – Igor Feb 12 '19 at 16:33
  • 2
    performance considerations? No. Go with whatever seems more readable to you. – Zohar Peled Feb 12 '19 at 16:35
  • I think the question might be more relevant for a "coding standard" discussion rather than performance. I updated the question – Claudiu Constantin Feb 12 '19 at 16:38
  • This is somewhat opinion-based although I see no reason for using a List in this case. An array is more concise, performant and readable. – Meta-Knight Feb 12 '19 at 16:41
  • You can follow generic rule to use more restricted interface which in many case can be considered as a good coding standard but again there can be caveats and exceptions depending on specific requirements. – Dmytro Mukalov Feb 12 '19 at 16:48
  • 1
    Why downvotes? The question is perfectly valid. – Vlad Feb 12 '19 at 17:08
  • Performance-wise arrays are a little bit faster as the compiler optimizes foreach loops over arrays by omitting the iterator/enumerator pattern (which would do a method call for each element) it would normally use and instead directly accesses the array indices. But like others have said this is negligible and has no noticeable realworld impact in your case. – ckuri Feb 12 '19 at 19:59

0 Answers0