I want to add a new property bool IsValid to my class below. I want this property to be NOT Required and set to false by default. I am using this object for wcf purposes, how do I set the default value to false?
[DataContract]
public class OrderLineItem : IExtensibleDataObject
{
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember]
public Guid LineItemID { get; set; }
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public string ProductID { get; set; }
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public decimal Quantity { get; set; }
}
Update: I answered it thinking about how to define a default value for any arbitrary type, but, as @HatSoft mentioned in the comment, you don't need to do anything to set false
as the default value of a bool
property, since it's already the default value for that type. I'll leave this answer for the general case, though.
There's no way to set the default value on the [DataMember] attribute itself, but you can use an [OnDeserializing] callback to set it. This way, if it doesn't come from the wire, it will have the value set by the code which ran before the deserialization.
[DataContract]
public class OrderLineItem : IExtensibleDataObject
{
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember]
public Guid LineItemID { get; set; }
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public string ProductID { get; set; }
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public decimal Quantity { get; set; }
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public bool IsValid { get; set; }
[OnDeserializing]
void BeforeDeserialization(StreamingContext ctx)
{
this.IsValid = false;
}
}
by default it will be false, so nothing else needs to be done.
[DataMember]
public bool IsValid { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With