0

I'm catching up with what's new in .NET 6+ (most of my knowledge is still .NET 4.8-era). One problem I continunally run into is the laborious process of parsing network protocol messages in C#. Now, with .NET having Span<byte>, is there a C-like way where I can cast a byte array into a struct? Not sure if ref struct are designed for this.

atanamir
  • 4,833
  • 3
  • 24
  • 20
  • 1
    No, a [`ref struct`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#ref-struct) is not what you're looking for. There are no guarantees to how objects are laid out in memory, so you can't cast raw memory directly to an object. Instead you'll have to do the correct thing and parse it – MindSwipe May 30 '22 at 05:53
  • If the stuff in the struct is a fixed size, can you do it with an explicitly laid out struct? – Caius Jard May 30 '22 at 07:05
  • Thanks, the `MemoryMarshal.Cast` is what I was looking for. I'm guessing that still must do a copy under-the-hood? – atanamir May 30 '22 at 07:18
  • The linked answer is slightly incomplete) (since it doesn't mention `MemoryMarshal.AsRef()`) so I'll link a more complete answer too. – Matthew Watson May 30 '22 at 07:51

0 Answers0