Can anybody explain why MemoryMarshal.Cast is defined for Span<T> but not for Memory<T>? Both of them are essentially pointers to contiguous memory; therefore I cannot see why Span cast is safer than Memory cast.

What I am looking for is a dream of any programmer working with communication protocols: non-copy conversion from any array to byte array, something like

public static byte[] ToBytes<A>(this A[] a) where A : struct {
    Memory<A> m = a;
    Memory<byte> mb = MemoryMarshal.Cast<A, byte>(m);       // Compiler error !
    ArraySegment<byte> ba;
    bool b = MemoryMarshal.TryGetArray(mb, out ba);
    return ba.Array;

What is more, other ways to do similar things also seem blocked (e.g. there is no cast from Span to Memory, TryGetArray does not work for Span...) I guess there is some good reason for all these no-no's; however, I cannot find one.

0 Answers