views:

950

answers:

2

Hi all,

I am trying to serialize and deserialize objects to/from a Byte array for network communication, I currently have an interface 'ISerialize'. However I got thinking there should be a more robust way to do this via reflection.

I've looked around a little bit at doing this using BinaryFormater, but I can't see if it will give me the control I require.

EDIT:

I would like to beable to decorate a class as Follows (Where fields can be any type so long as they are a system type or are also [Serializable]) [Serializable] public class MyClass{

     [NonSerialized]
     SomeOtherClass _classFeild;

     [Position (0)]
     UInt16 _field1;

     [Position (14)]
     UInt32 _feild2;

   //..........
}

And have the following functionality,

void Test (){
     MyObject = new MyClass ();
     Byte[] raw;
     raw  =  Serializer.Serialize (MyClass); // Results in _field1 at raw[0,1]
                                             //            _field2 at raw[14-18]

     MyClass Deserialized  = Serializer.Deserialize<MyClass> (raw); 
}

where all fields are swapped to / from network order (bigendian)


I would also rather white list fields to be serialized rather than blacklist those not to be. So the question is, is can I do this using the Framework, or do I need to write my own implementation?

+2  A: 

Sounds like a good fit for BinaryWriter and BitConverter.

sipwiz
I'm not sure that BinaryWriter gives me the functionality I'm looking for (See my edit). And indeed I am using BitConverter within ToHostOrder.
Courtney de Lautour
In your DeSerialize example why don't you use BitConverter.ToUInt32 rather than doing bit shift operations?
sipwiz
No logical reason, its an artefact from when I ported from VB6, it didn't occur to me to use BitConverter in that instance.
Courtney de Lautour
A: 

I've gone ahead and implemented this myself now, however I am still interested whether a built in method exists.

Courtney de Lautour