Saving Objects / Serialization

I am trying to make the transition from C to C #, and I have a few questions about storing objects in files and serializing.

In C, if you want to preserve the data structure, I was taught that saving it in text format, because the string is often not needed, and the binary that exists as a snapshot of the memory is often better because it does not require encoding / decoding and matching strings to fields. In C #, the approach seems different, it converts the fields of an object separately into a string or some other format, and then restores the object when necessary. I'm not sure how binary serialization works, but I think it is like converting data to some format and does not exist as a clean, unformatted memory snapshot.

Why is the "memory snapshot" method without encoding / decoding not used in C #? The only reason I can think of is compatibility with other codes and environments, and perhaps this is due to the complexity of objects versus regular structures.

+6
source share
2 answers

In C #, you do not have access to the object’s memory layout. You cannot take a snapshot of the memory for an object or create an object from a snapshot. In fact, you don’t even have dots (yes, you have them in unsafe code, but you rarely ever write unsafe code).

Even if you have access to the memory used by the object, it may not be saved to be saved to disk and then rebooted. If you are updating the .NET environment, you can get a better optimizer that decides to reorder the fields of the object differently or use a different memory alignment.

So, in short - there is no access to the object's memory, so you need to serialize the field by field.

The surface is that since .NET is reflected, serializing an object in this way is not difficult. This is actually much simpler than serializing a C ++ class that contains pointers to other C ++ classes.

+2
source

The .NET binary serialization format discards types as they would like to be stored, and puts them into some metadata so you know how to decode them (what type, what field name, etc.).

This is not primarily for interacting with .NET languages ​​- although it may be. This is for interacting with past and future versions of the same objects that can be written in such a way as to be resistant to these changes or, at least, to know in order to reject them.

In C, if you change the structure in any way - and you just used write() to store the memory, you probably also want to write some metadata so you can know if you have version right (and need to convert).

Another advantage is that .NET languages ​​know what to do with links. By default, C will be write() address, which will later be useless .. NET also supports the idea of ​​fields that should not be serialized (like a password) - another thing you will need to write manually in version C.

+1
source

All Articles