byte[] data = { 0x10, 0x20, 0x30, 0x40 }; int value; if (MemoryMarshal.TryRead(data, out value)) { Console.WriteLine($"Read value: {value}"); }
struct Employee { public int Id; public string Name; public decimal Salary; } byte[] data = { 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x80, 0x96, 0x98, 0x00 }; SpanIn the first example, we read a single integer value from a byte array. In the second example, we read a struct containing multiple fields from a byte array. The MemoryMarshal package is part of the System.Runtime.InteropServices namespace, which is included in the core .NET Framework.buffer = new Span (data); Employee employee; if (MemoryMarshal.TryRead(buffer, out employee)) { Console.WriteLine($"Read employee: Id={employee.Id}, Name={employee.Name}, Salary={employee.Salary}"); }