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?
views:
66answers:
3If 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.
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; }
}
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.