Search code examples
c#serializationruntimerandom-access

why we can't Serialize these objects?


why we can't Serialize objects into Random Access file ? and on the other hand we can serialize objects into sequential access file ?

""C# does not provide a means to obtain an object’s size at runtime. This means that, if we serialize the class, we cannot guarantee a fixed-length record size "" (from the book that i read in).

so we cannot read the the random access file because we don't know every object size in the file so how we could do seeking ??????


Solution

  • Any object marked with the SerializableAttribute attribute can be serialized (in most scenarios). The result from serialization is always directed to a stream, which may very well be a file output stream.

    Are you asking why an object graph cannot be deserialized partially? .NET serialization only [de]serializes complete object graphs. Otherwise you'll have to turn to other serialization formatters, or write your own.

    For direct random access to a file, you must open the file with a stream that supports seeking.

    EDIT:

    Seeking in the resulting stream from a serialization has no practical purpose - only the serialiation formatter knows what's in there anyway and should always be fed the very start of the stream.

    For persisting the data into other structures; do it in a two-stage process: First, target the serialization bytes to a [i.e. memory-backed] stream that you can read the size from afterwards, then write the data to the actual backing store, using said knowledge of size.

    You can't predict the size of a serialized object, because the serialized representation might differ a lot from the runtime representation.

    It it still possible to achieve exact control over output size, if you use only primitive types, and you write using a BinaryWriter - but that is not serialization per-se.