Well, anything other than myObject to byte[] will never work unless you have an explicit conversion or if myObject is byte[] . You need a serialization structure. There are many, including Protocol Buffers , which is dear to me and dear. This is quite "meager and average" both in space and in time.
You will find that almost all serialization schemes have significant limitations on what you can serialize, however - the protocol buffers are larger than some due to cross-platform.
If you can provide more requirements, we can help you more, but it will never be as easy as casting ...
EDIT: just to answer this:
I need my binary to contain bytes of objects. Only bytes, no metadata. compacted object to object. So I will be implementing custom serialization.
Please keep in mind that bytes in your objects are often referenced ... so you will need to figure out what to do with them.
I suspect you will find that designing and implementing your own custom serialization scheme is more complex than you imagine.
I would personally recommend that if you need to do this only for a few specific types, you will not bother to come up with a general serialization scheme. Just implement the instance method and the static method in all the types you need:
public void WriteTo(Stream stream) public static WhateverType ReadFrom(Stream stream)
One thing to keep in mind: things get more complicated if you have inheritance. Without inheritance, if you know what type you start with, you do not need to include type information. Of course, there is also a versioning question - do you need to worry about compatibility with previous versions and switching to other versions of your types?
Jon Skeet Sep 18 '09 at 20:02 2009-09-18 20:02
source share