`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

Reference types vs Value types

Reference types:

  • passed via reference
  • reside on the heap
  • subject to GC
  • inherits from System.Object

Value types:

  • passed via value
  • reside on the stack, CPU registers or the heap
  • no subject to GC
  • inherits from System.ValueType

Further read:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

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

https://www.infoworld.com/article/3043992/a-deep-dive-value-and-reference-types-in-net.html