Home
Blog
When to Use Arrays in C#
Updated
Dot Net Perls

When to Use Arrays in C#

Probably my favorite class in C# is the List. It expands to hold as many items as you want, and it can be set (through the generics syntax) to hold any element type you desire. But arrays in C# offer some clear benefits, too—though they are less often needed.

An array is different from a List mainly because it cannot resize its buffer on its own. An array of 100 elements will always have 100 elements (though elements could be null). For this reason, we should prefer arrays only when we know the exact element count beforehand—like for a buffer of bytes we read data into.

Arrays are preferred only when:

Performance is critical, as arrays may have lower overhead for element accesses in some cases than Lists.
The element count is fixed (as in a buffer we read data into).
Memory usage is an issue—arrays have somewhat lower memory usage than Lists because they cannot resize their buffer, and will never reallocate (which leads to garbage collection).

Basically, if your program's goal is to read strings from a file, you will want a List. But if you want to store 10 strings in a class for later use, a string array is a better choice. Usually the List is the better first choice.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen