Here is a generic and unsafe variant if you care about performance and don't want to mess with GC
static unsafe void StructToByteArr<T>(ref T obj, Span<byte> dest) where T : unmanaged { fixed (void* pSrc = &obj, pDest = dest) { Buffer.MemoryCopy(pSrc, pDest, dest.Length, sizeof(T)); } } static unsafe void StructToByteArr<T>(ref T obj, byte[] dest, int destOffset) where T : unmanaged { StructToByteArr(ref obj, new Span<byte>(dest, destOffset, sizeof(T))); } static unsafe byte[] StructToByteArr<T>(ref T obj) where T : unmanaged { var result = new byte[sizeof(T)]; StructToByteArr(ref obj, result, 0); return result; }
You can remove ref if you're passing a struct smaller than the size of a pointer.