Data structures in .NET

In table below official recommendations for choosing data structure for your needs:

GenericNon-GenericThread safePurpose
DictionaryHashtableConcurrentDictionarykey value pairs, lookup
ListArrayImmutableListaccess items by index
QueueConcurrentQueueFIFO queue
StackConcurrentStackLIFO queue
LinkedListaccess items sequentially
ObservableCollectionnotfications after modification
SortedListImmutableSortedSetauto sorted collection
HashSetImmutableHashSetdictionary of just keys (high performance set operations)

Further read:

https://learn.microsoft.com/en-us/dotnet/standard/collections/

Strings in .NET

  • sequential collection of chars
  • immutable
  • max 2GB or about 1 billion characters
  • reference type
  • are interned – CLR saves memory by maintaining a table, called the “intern pool”, that contains a single reference to each unique literal string declared or created programmatically in your program.

Further read:

https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-7.0

https://learn.microsoft.com/en-us/dotnet/api/system.string.intern?view=net-6.0#remarks

`ref struct` types

  • added as part of C# 7.2.
  • defined with ref struct StructName
  • always on the stack
  • never part of heap
  • cannot be element of an array
  • cannot be field type of reference type
  • can’t implement interfaces
  • can’t be boxed
  • can’t be type argument
  • can’t be captured by closure of lambda or local function
  • can’t be used in async methods
  • can’t be used in iterators

Further read:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct