Skip to main content

How to Copy a ReadOnlyMemory<T> into an Array with ToArray in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

ToArray() copies the items of a ReadOnlyMemory<T> into a new array of their own. Use it when a method wants an array, or when you need a copy that you can change.

Microsoft's reference for ReadOnlyMemory<T>.ToArray: Copies the contents from the memory region into a new array. A ReadOnlyMemory<T> is a view of a block of items, often part of an array. It has no items of its own, and a method that wants an array won't take it. ToArray is the bridge, and its remarks say so: ToArray allocates on the heap and so should generally be avoided. However, it is sometimes necessary to bridge the gap with APIs written in terms of arrays. "Allocates on the heap" means that every call makes a new array.

Syntax​

Syntax
ReadOnlyMemory<T> <memory> = new(<array>, <start>, <length>);
T[] <copy> = <memory>.ToArray();
PartWhat it is
TThe type of the items, such as int or byte
new(<array>, <start>, <length>)One way to get a ReadOnlyMemory<T>: a view of <length> items of <array>, starting at position <start>. Positions start at 0
<memory>.ToArray()Copies the items into a new array
T[] <copy>The new array, which holds its own copy of the items

The constructor, in the reference's words: Creates a new memory region over the portion of the target array beginning at a specified position and including a specified number of elements. When a method hands you a ReadOnlyMemory<T>, only the second line is yours.

The Example​

A console app called ReadOnlyMemoryToArray keeps a week of temperatures in an array, and takes a ReadOnlyMemory<int> over its last three days. It copies those three into an array with ToArray, sorts the copy, and then changes the week, to show which of the two sees the change.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ReadOnlyMemoryToArray
cd ReadOnlyMemoryToArray
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ReadOnlyMemoryToArray/ReadOnlyMemoryToArray.csproj:
Determining projects to restore...
Restored /Users/you/source/ReadOnlyMemoryToArray/ReadOnlyMemoryToArray.csproj (in 43 ms).
Restore succeeded.

dotnet new console -n ReadOnlyMemoryToArray creates a folder named ReadOnlyMemoryToArray with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ReadOnlyMemoryToArray.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the week, and a view of its last three days:

Program.cs (the week and a view of it)
// A week of temperatures, and a read-only view of its last three days.
int[] week = [18, 21, 19, 24, 22, 25, 23];
ReadOnlyMemory<int> lastThree = new(week, 4, 3);

week holds 7 temperatures. new(week, 4, 3) creates a ReadOnlyMemory<int> over 3 of them, starting at position 4: the values 22, 25 and 23.

Then copy them:

Program.cs (the copy)
// ToArray copies the three numbers into a new array of their own.
int[] copy = lastThree.ToArray();
Console.WriteLine($"Copy: {string.Join(", ", copy)} ({copy.Length} items)");

lastThree.ToArray() returns an int[] that holds the three numbers. string.Join(", ", copy) puts a comma between them, and copy.Length counts them.

Then do something that needs an array:

Program.cs (sort the copy)
// An array can be sorted in place. The read-only memory can't.
Array.Sort(copy);
Console.WriteLine($"Sorted copy: {string.Join(", ", copy)}");

Array.Sort puts the items of an array in order, inside that same array. It takes an array, so it can sort the copy but not the memory.

Last, change the week:

Program.cs (change the week)
// Change the week: the memory sees it, the copy doesn't.
week[4] = 30;
Console.WriteLine($"Memory now: {string.Join(", ", lastThree.ToArray())}");
Console.WriteLine($"Copy still: {string.Join(", ", copy)}");

week[4] = 30; changes the first of the three days in the original array. Then the program prints the memory, through a fresh ToArray(), and the copy.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Copy: 22, 25, 23 (3 items)
Sorted copy: 22, 23, 25
Memory now: 30, 25, 23
Copy still: 22, 23, 25

macOS-style terminal window titled Terminal — ReadOnlyMemoryToArray showing dotnet run printing Copy: 22, 25, 23 with 3 items, Sorted copy: 22, 23, 25, Memory now: 30, 25, 23, and Copy still: 22, 23, 25

ToArray copied the last three days, 22, 25, 23, into an array of 3 items, and Array.Sort put the copy in order: 22, 23, 25. After week[4] = 30, the memory showed 30, 25, 23, because it reads its items from week. The copy still held 22, 23, 25: it's a separate array, so the change didn't reach it.

The Complete File​

macOS-style code window titled Program.cs — ReadOnlyMemoryToArray showing an array of seven temperatures, a ReadOnlyMemory of int over its last three items, ToArray copying them into a new array that Array.Sort puts in order, and a change to the week that the memory shows and the copy doesn't

Program.cs
// A week of temperatures, and a read-only view of its last three days.
int[] week = [18, 21, 19, 24, 22, 25, 23];
ReadOnlyMemory<int> lastThree = new(week, 4, 3);

// ToArray copies the three numbers into a new array of their own.
int[] copy = lastThree.ToArray();
Console.WriteLine($"Copy: {string.Join(", ", copy)} ({copy.Length} items)");

// An array can be sorted in place. The read-only memory can't.
Array.Sort(copy);
Console.WriteLine($"Sorted copy: {string.Join(", ", copy)}");

// Change the week: the memory sees it, the copy doesn't.
week[4] = 30;
Console.WriteLine($"Memory now: {string.Join(", ", lastThree.ToArray())}");
Console.WriteLine($"Copy still: {string.Join(", ", copy)}");

Common Mistakes​

MistakeWhat happensDo this instead
Assigning the memory to an array variableint[] copy = lastThree; didn't build: error CS0029: Cannot implicitly convert type 'System.ReadOnlyMemory<int>' to 'int[]'Call ToArray(): int[] copy = lastThree.ToArray();
Passing the memory to string.Joinstring.Join(", ", lastThree) printed System.ReadOnlyMemory<Int32>[3], not the numbers. The ToString reference: For ReadOnlyMemory<T> with char elements, returns an instance of string that represents the characters pointed to by the memory. Otherwise, returns a String with the name of the type and the number of elements.Join a copy: string.Join(", ", lastThree.ToArray()) printed 22, 25, 23
Passing the memory to a method that wants an arrayArray.Sort(lastThree); didn't build: error CS1503: Argument 1: cannot convert from 'System.ReadOnlyMemory<int>' to 'System.Array'Pass a copy, as the example does: Array.Sort(copy);

FAQ​

How do I turn a ReadOnlyMemory of bytes into a byte array?​

The same way: ToArray() on a ReadOnlyMemory<byte> returns a byte[].

Program.cs (bytes)
using System.Text;

// Bytes work the same way: a ReadOnlyMemory<byte> becomes a byte[].
byte[] source = [72, 105, 33];
ReadOnlyMemory<byte> data = source;

byte[] bytes = data.ToArray();
Console.WriteLine($"{bytes.Length} bytes: {string.Join(" ", bytes)}");
Console.WriteLine($"As text: {Encoding.ASCII.GetString(bytes)}");
Output
3 bytes: 72 105 33
As text: Hi!

ReadOnlyMemory<byte> data = source; makes a memory over a whole array without a constructor. The reference for that conversion: Defines an implicit conversion of an array to a ReadOnlyMemory<T>. Encoding.ASCII.GetString turns the copied bytes back into text.

Does ToArray return the same array every time?​

No. Each call makes a new array, even when the memory covers a whole array:

Program.cs (two copies)
int[] week = [18, 21, 19, 24, 22, 25, 23];

// A memory over the whole array, copied twice.
ReadOnlyMemory<int> all = week;
int[] first = all.ToArray();
int[] second = all.ToArray();

Console.WriteLine($"Same items: {first.SequenceEqual(week)}");
Console.WriteLine($"Same array as week: {ReferenceEquals(first, week)}");
Console.WriteLine($"Two calls, same array: {ReferenceEquals(first, second)}");
Output
Same items: True
Same array as week: False
Two calls, same array: False

SequenceEqual compares the items, and ReferenceEquals says whether two variables point to the very same array. The copy held the same items as week but was a different array, and two calls made two different arrays. That's the heap allocation the remarks warn about.

Conclusion​

ToArray() copies the items of a ReadOnlyMemory<T> into a new T[]. The copy is yours: you can sort it, pass it to methods that want an array, and changes to the original items don't reach it. Each call makes a new array, so keep the copy in a variable when you use it more than once, as the example does with copy.

Additional Resources​