Reputation: 13087
I've noticed that if a Boolean property in a data contract does not emit a default property, e.g.
[DataMember(Order = 0, IsRequired = true, EmitDefaultValue = false)]
public bool IsSet { get; set; }
then setting the property to false results in a serialization error. This seems counter-intuitive, because the property has been set, it's just that it's been set to false. The solution is to always configure Boolean properties to emit a default value, then true will come across the wire as true, and false as false.
Just curious: is this a bug in System.Runtime.Serialization or the inevitable result of Boolean type semantics?
Upvotes: 3
Views: 1695
Reputation: 73
To avoid the conflict, you could use nullable bool (bool?) so if the value is explicitly set to false, it will be serialize as expected. Of course, make sure nullable bool data type is something your system can handle.
[DataMember(Order = 0, IsRequired = true, EmitDefaultValue = false)]
public bool? IsSet { get; set; }
Upvotes: 0
Reputation: 28530
Your question is a little confusing, but I think the behavior you seem to be sqying you're seeing is not a bug, or anything to do with the booleans.
The operation contract is marked with IsRequired
set to true. By default, EmitDefaultValue
is set to true, but in the posted code it's been set to false.
The EmitDefaultValue
attribute indicates whether or not to serialize the value if it is the default value (in other words, if the property was set to false
, it would not serialize that property per your current definition).
Since the property is marked as required, if you set the value to false
the serialization will fail (if EmitDefaultValue
is false) because you're giving contradictory directions - you're saying this property is required for serialization, but don't serialize it if it's the default (false).
In a way I guess you could say it's because of the nature of boolean (it's either true or false, and false is the deafult), but in reality it's because of the way IsRequired
and EmitDefaultValue
interact.
Take a look at Data Member DefaultValues, specifically the "Interaction with IsRequired" section.
Upvotes: 3