12.17 Preventing Object Items from Being Serialized

 <  Day Day Up  >  

You want to prevent the serialization of a data member within an object.


Technique

To prevent serialization on a member variable from occurring within a class, apply the NonSerialized attribute. When the serialization process occurs, the formatter checks each data item being serialized for that attribute. If it is present, the item is skipped and not serialized to the data stream:

 
 [ Serializable, ] public class SerializedObject {     public string stringVariable = "This is a public string variable";     public int intVariable = 42;     // this var is non-serialized     [NonSerialized]     private int nonInt = 42;     [XmlIgnore]     public int NonSerializedInteger     {         get         {             return nonInt;         }         set         {             nonInt = value;         }     } } 

The XmlSerializer class is the only serialization object that serializes object properties. You might want to prevent serialization of properties as well. However, the XmlSerializer utilizes a different attribute, named XmlIgnore . If you place this attribute on any public member variables or properties, the XmlSerializer skips that item during serialization.

Comments

Section 12.16, "Recreating Objects with Deserialization," mentioned that when an object is deserialized, no initialization code, such as the constructor, is called. If you know that a certain data item within your class will be invalid upon deserialization, or it at least has the potential to become invalid, then you should consider applying the NonSerialized attribute if using binary or SOAP serialization or the XmlIgnore attribute if using XML serialization. Additionally, you should also check whether any data items contain sensitive information. For instance, if a private member variable was a string containing credit card information, then serializing that string presents a large security and privacy risk. Therefore, you should either consider not serializing that data item or at least applying some type of encoding or cryptography to prevent the unintentional security risk.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net