Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Datacontract - Does it support nullable data member?

Tags:

wcf

    [DataMember]
    public int? NumberOfPages;   //////////// Is this supported????
    [DataMember]
    public bool? Color;          //////////// Is this supported????
    [DataMember]
    public int? BulkQuantity;
    [DataMember]
like image 632
Pinu Avatar asked Mar 11 '10 16:03

Pinu


4 Answers

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.

like image 170
marc_s Avatar answered Nov 11 '22 15:11

marc_s


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

Nullable types are fully supported by the data contract serializer.

like image 41
Andrew Hare Avatar answered Nov 11 '22 15:11

Andrew Hare


@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.

like image 4
nwelebny Avatar answered Nov 11 '22 15:11

nwelebny


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;
            }
        }
    }
like image 1
Neeraj Kumar Avatar answered Nov 11 '22 16:11

Neeraj Kumar