.NET by Patrik

Array or List — Which Is Better for Logging?

The choice between arrays and lists communicates intent and affects performance and safety.

When data is only needed for display or logging, an array represents a fixed snapshot and avoids accidental changes:

string[] names =
    source.Select(x => x.Name).ToArray();

logger.LogInformation(
    "Names=[{Names}]",
    string.Join(", ", names));

Lists are useful when the collection must be modified or extended later:

var names =
    source.Select(x => x.Name).ToList();

names.Add("NewItem");

Choosing the right type makes the code easier to understand and prevents unintended side effects.

collections
array
list
performance
basics

Comments