Information Technology Reference
In-Depth Information
and the order of the variables. The order is the order declared in the class.
(By the way, this fact means that rearranging the order of variables in a class
or renaming variables breaks the compatibility with files already created.)
Also, I have demanded the SerializationFormatter security permission.
GetObjectData could be a security hole into your class if it is not properly
protected. Malicious code could create a StreamingContext, get the values
from an object using GetObjectData, serialize modified versions to
another SerializationInfo, and reconstitute a modified object. It would
allow a malicious developer to access the internal state of your object,
modify it in the stream, and send the changes back to you. Demanding the
SerializationFormatter permission seals this potential hole. It ensures that
only properly trusted code can access this routine to get at the internal
state of the object.
But there's a downside to implementing the ISerializable interface. You
can see that I made MyType sealed earlier. That forces it to be a leaf class.
Implementing the ISerializable interface in a base class complicates serial-
ization for all derived classes. Implementing ISerializable means that every
derived class must create the protected constructor for deserialization. In
addition, to support nonsealed classes, you need to create hooks in the
GetObjectData method for derived classes to add their own data to the
stream. The compiler does not catch either of these errors. The lack of a
proper constructor causes the runtime to throw an exception when read-
ing a derived object from a stream. The lack of a hook for GetObjectData()
means that the data from the derived portion of the object never gets saved
to the file. No errors are thrown. I'd like the recommendation to be “imple-
ment Serializable in leaf classes.” I did not say that because that won't
work. Your base classes must be serializable for the derived classes to be
serializable. To modify MyType so that it can be a serializable base class,
you change the serializable constructor to protected and create a virtual
method that derived classes can override to store their data:
using global ::System.Runtime.Serialization;
using global ::System.Security.Permissions;
[ Serializable ]
public class MyType : ISerializable
{
private string label;
 
Search WWH ::




Custom Search