Pinu
Pinu

Reputation: 7520

WCF Datacontract - Does it support nullable data member?

    [DataMember]
    public int? NumberOfPages;   //////////// Is this supported????
    [DataMember]
    public bool? Color;          //////////// Is this supported????
    [DataMember]
    public int? BulkQuantity;
    [DataMember]

Upvotes: 27

Views: 27472

Answers (4)

Neeraj Kumar
Neeraj Kumar

Reputation: 779

In my case It looks like that the Nullable Integer passed in is treated as Empty String and NOT Null Value

So here is how I handle the nullable in the code

    [XmlIgnore]
    public int? NumberOfPagesCount{ get; set; }

    [XmlElement("NumberOfPages")]
    public string NumberOfPagesText
    {
        get { return this.NumberOfPagesCount.HasValue ? this.NumberOfPagesCount.Value.ToString("F2") : string.Empty; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                this.NumberOfPagesCount= Convert.ToInt32(value);
            }
            else
            {
                this.NumberOfPagesCount= null;
            }
        }
    }

Upvotes: 1

nwelebny
nwelebny

Reputation: 41

@Kahoon and Batwad:

We solved this problem by using the nullable<> or ? type in two steps:

  1. In the class containing the generic field, define the field as follows:

    nullable<GenType> MyField {get; set;}
    
  2. In the data contract that uses this baseclass, you can define which elements are known to the serializer/deserializer using some annotation-like tags. Here, we defined for example:

    [Serializable]
    [DataContract]
    [KnownType(typeof(BaseClass<nullable<DateTime>>))]
    

    Instead of BaseClass<nullable<DateTime>> you can use BaseClass<DateTime?>, I think.

After this, the serialization of generic null values worked for us.

Upvotes: 4

Andrew Hare
Andrew Hare

Reputation: 351566

Yes, please see Types Supported by the Data Contract Serializer:

Nullable types are fully supported by the data contract serializer.

Upvotes: 7

marc_s
marc_s

Reputation: 754993

Yes, of course!

You should have no trouble whatsoever to create nullable data members, they'll be handled in the resulting WSDL/XSD as "xs:nillable=true" members. No problem at all.

Upvotes: 33

Related Questions