In the C# programming language, structs or structure types are value types that allow faster access because they are usually stored in the stack. However, although structs reduce memory footprints and eliminate garbage collection overheads, they are not a good choice in high-performance scenarios where memory allocation and deallocation in the stack is critical.
In such scenerios, C# provides a better alternative called a ref struct. Whereas both structs and ref structs are allocated in the stack and don’t require garbage collection, there are subtle differences between the two types and their use cases.
In this article we’ll examine ref structs, their features and benefits, and how we can use them in C#. To work with the code examples provided in this article, you should have Visual Studio 2022 Preview installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.