Googling around this I am getting a lot of mixed results from old .NET versions and so on.
Given a message protocol like:
- Bytes 0-1: Message Type ID
- Byte 2: Message number
- Byte 3: Payload size
- Bytes 4...n-1: Payload data
- Bytes n,n+1: Checksum
I want to write a C# class Message
which can serialize and deserialize with byte[]
which might ideally have as its core something like this (I use properties but members are just fine if it matters)
class Message
{
public Int16 Type {get; set;}
public byte Number {get; set;}
public byte PayloadSize {get; set;}
public byte[] Payload{get; set;}
public Int16 CheckSum {get; set;}
}
Of course to write code to do this is easy enough but I know .NET does have some automatic (de)serialization functionality which would be nice to avoid coding errors in dull boiler-plate code. However I need to guarantee the ordering, etc so the protocol is followed.
Does modern .NET Framework (4.x) allow a way to automate this and if so, what is it? How is attribute ordering controlled for instance? And how would I actually instance and serialize objects from/to byte[]
?
I should add, I know one could write this sort of thing using reflection, but a solution that is more work than the problem it solves isn't of great use. Neither am I keen on using some code library unless very well-tested, this is really a question about C# capabilities built-in.