none
Why Memory and ReadOnlyMemory are struct? RRS feed

  • Question

  • Why the types Memory and ReadOnlyMemory are struct instead of class? As they generally are used on asynchronous calls and are moved to the heap.
    Tuesday, June 8, 2021 2:18 PM

All replies

  • Hi

    Span<Message> valSpan stackalloc Message[1] ;
    valSpan[0] =Message {Header = 123, Data = 456 } ;
    Span<byte> bytes = MemoryMarshal.Cast<Message, byte>(valSpan); // has a length of 8
    Note that I am using Span<T> here. You can do much the same with Memory<T> if necessary - but you need a support array or similar, which will usually require allocation - if not the array, then a custom MemoryManager<T> :

    var arr = new message[1] ;
    arr[0] = new message {Header = 123, Data = 456 } ;
    Memory<byte> bytes = MemoryMarshal.Cast<Message, byte>(arr); // has a length of 8
    Essentially, you are very close here:

    MemoryMarshal.CreateReadOnlySpan(ref message, 1)
    The trick, however, is to use MemoryMarshal.Cast<TFrom

    Tuesday, June 8, 2021 2:42 PM
  • The only significant difference between a structure and a class is the default status of members.  In a structure, they are public while in a class they are private.

    Declared objects do not occupy space on the heap.   Only allocated (via new, malloc, etc) objects do.

    For obvious reasons, read only memory can only bu used for declared object defined as const or things like string literals which are non-modifiable.

    Thursday, June 10, 2021 12:26 AM