.NET 8 and C# 12 — Inline Arrays
Inline Arrays is a new C# 12 feature that brings performance improvements when working with Arrays. In this article, I present how to declare and use an Inline Array.
Inline Arrays allow you to create an array of fixed size in a struct
type. One advantage of this is that structs
are value types, and memory for struct
instances are usually allocated on the stack (unless subjected to ‘boxing,’ which is the process of converting a value type to a reference type, or if they are fields within a class or elements of an array), which results in more efficient memory usage, while arrays
are reference types, and their memory is stored on the heap.
For demonstration purposes, I created a console application with .NET 8, and I configured the LangVersion
in the .csproj file with the preview
value:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
</Project>
To create an Inline Array you need to do the following:
- Declare a
struct
- Add the
InlineArray
attribute (using the namespaceSystem.Runtime.CompilerServices
) with the length of the array - Declare a private member with the type you want. The name of this private member can be any name (you will not use it anyway, this is only going to be used by the compiler).
In the code below there is an example of an Inline Array:
[System.Runtime.CompilerServices.InlineArray(10)]
public struct InlineArrayDemo
{
private int _element;
}
To use an Inline Array, it’s similar to using a normal Array, but you do not need to specify the size, as it already has a fixed size defined. A difference when comparing to arrays is that, unlike a normal Array, an Inline Array does not have a Lenght property, and it’s not possible to use LINQ.
In the code below there is an example of how can you initialise and iterate over an Inline Array:
var inlineArray = new InlineArrayDemo();
for (int i = 0; i < 10; i++)
{
inlineArray[i] = i;
}
foreach (var item in inlineArray)
{
Console.Write($"{item} ");
}
// Output:
0 1 2 3 4 5 6 7 8 9
Conclusion
Inline Arrays are used by the .NET runtime team and other library authors to improve performance in your apps. You most probably will not need to declare your own InlineArray, but you use them transparently when they’re exposed as System.Span<T>
or System.ReadOnlySpan<T>
objects from runtime APIs, so this is something that is good to understand how it works and what the benefits are. As presented, Inline Arrays brings performance improvements when working with Arrays, as the memory for them is allocated on the stack, leading to more efficient memory usage.
This is the link for the project in GitHub: https://github.com/henriquesd/DotNet8Examples
If you like this demo, I kindly ask you to give a ⭐️ in the repository.
Thanks for reading!
References