Yahoo free web hosting - CHAPTER 17 562 UNDERSTANDING OBJECT SERIALIZATION //
Friday, March 21st, 2008CHAPTER 17 562 UNDERSTANDING OBJECT SERIALIZATION // Save an instance of UserPrefs to file. BinaryFormatter binFormat = new BinaryFormatter(); Stream fStream = new FileStream(@”C:user.dat”, FileMode.Create, FileAccess.Write, FileShare.None); binFormat.Serialize(fStream, up); fStream.Close(); Console.ReadLine(); } At this point, an instance of UserPrefs (version 1.0) has been persisted to C:user.dat. Now, what if you updated the definition of UserPrefs class with two new fields: [Serializable] class UserPrefs { public string objVersion = “2.0″; public ConsoleColor BackgroundColor; public ConsoleColor ForegroundColor; // New! public int BeepFreq; public string ConsoleTitle; public UserPrefs() { BeepFreq = 1000; ConsoleTitle = “My Console”; BackgroundColor = ConsoleColor.Black; ForegroundColor = ConsoleColor.Red; } } Imagine this same application now attempts to deserialize the instance of the persisted UserPrefs object version 1.0 as so (note the previous serialization logic has been removed in order for this example to work): static void Main(string[] args) { // Load an instance of UserPrefs (1.0) to memory? UserPrefs up = null; BinaryFormatter binFormat = new BinaryFormatter(); Stream fStream = new FileStream(@”C:user.dat”, FileMode.Open, FileAccess.Read, FileShare.None); up = (UserPrefs)binFormat.Deserialize(fStream); fStream.Close(); Console.ReadLine(); } You will find a runtime exception is thrown: Unhandled Exception: System.Runtime.Serialization.SerializationException: Member ‘BeepFreq’ in class ‘ VersionedObject.UserPrefs’ is not present in the serialized stream and is not marked with System.Runtime.Serialization.OptionalFieldAttribute. The problem is that the original UserPrefs object persisted to C:user.dat did not have storage for the two new fields found in your updated class definition (BeepFreq and ConsoleTitle). Clearly, this is problematic, as it is quite natural for a serialized object to evolve over its lifetime. Prior to .NET 2.0, the only way to account for the possibility that previously persisted objects may not have each and every field of the latest and greatest version of the class was to implement
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.