views:

66

answers:

3

That is, I'd like my data to go one way - feed into a class, but then prevent it from saving out during a serialize operation. What's the best way to go about that?

A: 

If you like the full control over the serialization process you can implement the interface ISerializable.

Also implement the special constructor.

EDIT: I meant IXmlSerializable. Thanks John.

schoetbi
+2  A: 

The simplest way is to serialize a property that does Set correctly but always returns a fixed, fake value on Get. For example, if the property were called Password, you'd create a SerializablePassword property that fits the above design, while not serializing the original.

edit

Here's Ani's sample, formatted, with one change:

[XmlIgnore]
public string Password { get; set; }

[XmlElement("Password")]
public string SerializablePassword
{
  get { return null; }
  set { Password = value; }
}
Steven Sudit
Well, yes, I considered that. However, if I did something like get { return null; }, then I couldn't access the value internally.
end-user
@end-user: Setting `SerializablePassword` would set the same backing field as `Password`, so getting `Password` would work just fine.
Steven Sudit
+1 @ Steven: Something like this, if I understand correctly? Good idea, bit of a hack though.. :)[XmlIgnore]public string Password {get; set;}public string SerializablePassword {get {return null;}set {Password = value; }}
Ani
@Ani: Yes, that's right. I just stole your sample, adding an attribute to control the name of the XML element. But, yes, it's admittedly something of a hack. If `SerializablePassword` could be made `protected`, that would be an improvement.
Steven Sudit
A: 

Ok, I tried the return null; suggestion, but it doesn't work; it fails to deserialize. However, here's a workaround:

public List<Program> Programs
{
    get
    {
        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
        for (int i = 0; i < stackTrace.FrameCount; i++)
        {
            if ("XmlSerializationWriterApplication".Equals(stackTrace.GetFrame(i).GetMethod().ReflectedType.Name))
            {
                return null;
            }
        }
        return programs;
    }
    set { programs = value; }
}

While probably not very performant, this examines the StackTrace to see who called the get - and if it's the Serializer/Writer, it returns nothing.

end-user