A post on one of the microsoft groups prompted some research, I was bent upon finding out a solution one way or the other.
[Serializable]
public class Tested
{
private string _value;
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
}
When you serialize the class above, after setting the property Value to, say "test" using the default XML serializer that comes with the BCL (XMLSerializer instance) you will get something like this as an output -
<?xml version="1.0" encoding="IBM437"?>
<Tested xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-nstance">
<Value>test</Value>
</Tested>
What will you do to make the default serializer ignore a public property? Lets start with a public member variable. Mark it as [NonSerialized] ofcourse. So if the class were something like this
[Serializable]
public class Tested
{
[NonSerialized]
public string Value;
}
and you serialized an instance of this class using XMLSerializer, the NonSerialized attribute is totally ignored, and you get
<?xml version="1.0" encoding="IBM437"?>
<Tested xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-nstance">
<Value>test</Value>
</Tested>
So the XMLFormatter is not a solution at all. Also, you cannot mark a property with NonSerialized, as this attribute applies to fields only
Next, use a SoapFormatter and Serialize this instance, sending the instance as a graph you get
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Tested id="ref-1" xmlns:a1="http://schemas...">
</a1:Tested>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
“Value” is not serialized here, which is good for me and I can move back to my original problem, the one where I want the serializer/formatter to ignore a public property.
[Serializable]
public class Tested
{
[NonSerialized]
private string _value;
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
}
Worked
Lessons learnt
XMLSerializer
Serializes public properties and fields, doesn't matter if you mark them as NonSerializable or not.
Also, I must note that properties are serialized; even thought they are actually methods internally, the XMLSerializer calls them.
SOAPFormatter
Serializes all fields (no properties), and respects NonSerializable.
Is this differing behaviour by design, or am I missing some configuration setting
Whatever be the case, I would still advocate implementing ISerializable, and writing your own serialization/deserialization code.
Posted
Fri, Jan 28 2005 5:37 AM
by
rsakalley