Memory does not support stack allocated memory 2 (original) (raw)
At the end of rule 2, this page says:
The DisplayBufferToConsole method now works with virtually every buffer type imaginable: T[], storage allocated with stackalloc, and so on. You can even pass a String directly into it!
There are two issues here:
Memory<T>can't be used with memory allocated on the stack. One link that talks about this, which appears to be the main source for this article, can be seen here. This link says:
Memory<T> cannot be backed by "transient" unmanaged memory; e.g., it is forbidden to back a Memory<T> with stackalloc.
You can also verify for yourself that the following code will not compile:
Memory<int> mem = stackalloc int[10];
- The 2nd issue is that a string can't be passed directly into DisplayBufferToConsole. If this is tried, then the C# compiler complains:
Error CS1503 Argument 1: cannot convert from 'string' to 'System.Memory'
Maybe whoever wrote this intended to provide a converter to translate a string into a Memory<T> type. But, if so, it is not present.
I am using the latest version of VS 2019 Community - 16.10.4, which I recently upgraded to. I am also using .NET 6, preview 5 (or maybe preview 6 if it is included with the latest VS 2019 16.10.4 update).
In any case, I would recommend changing the text to read:
The DisplayBufferToConsole method now works for any type of memory allocated on the heap. Memory<T> can't be used with memory allocated on the stack with stackalloc. This is only supported with Span<T>.
The Memory Struct article should also mention that Memory<T> can't be used on stack allocated memory.
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 4819512e-1044-1c57-0de1-447164220fd5
- Version Independent ID: d6cf8d26-fb2f-7138-f0c7-ab529a5b9cde
- Content: Memory and Span usage guidelines
- Content Source: docs/standard/memory-and-spans/memory-t-usage-guidelines.md
- Product: dotnet-fundamentals
- GitHub Login: @tdykstra
- Microsoft Alias: tdykstra