Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Default Value Of WCF DataMember Property

Tags:

c#

wcf

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; }
}
like image 730
Nick LaMarca Avatar asked Dec 04 '22 15:12

Nick LaMarca


2 Answers

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;
    }
}
like image 184
carlosfigueira Avatar answered Dec 10 '22 09:12

carlosfigueira


by default it will be false, so nothing else needs to be done.

[DataMember] 
public bool IsValid { get; set; }
like image 39
HatSoft Avatar answered Dec 10 '22 10:12

HatSoft