Memory<T> and ReadOnlyMemory<T>
There are two visual differences between
Span<T>. The first one is that
Memory<T> type doesn’t contain
ref modifier in the header of the type. In other words, the
Memory<T> type can be allocated both on the stack while being either a local variable, or a method parameter, or its returned value and on the heap, referencing some data in memory from there. However, this small difference creates a huge distinction in the behavior and capabilities of
Memory<T> compared to
Span<T> that is an instrument for some methods to use some data buffer, the
Memory<T> type is designed to store information about the buffer, but not to handle it. Thus, there is the difference in API.
Memory<T>doesn’t have methods to access the data that it is responsible for. Instead, it has the
Spanproperty and the
Slicemethod that return an instance of the
Pin()method used for scenarios when a stored buffer data should be passed to
unsafecode. If this method is called when memory is allocated in .NET, the buffer will be pinned and will not move when GC is active. This method will return an instance of the
MemoryHandlestructure, which encapsulates
GCHandleto indicate a segment of a lifetime and to pin array buffer in memory.
This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.
Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.