Search code examples
wcfserializationdatacontractdatamember

Can I prevent a specific datamember from being deserialized?


I have a datacontract like this

[DataContract]
class MyDC 
{
    [DataMember]
    public string DM1;

    [DataMember]
    public string DM2;

    [DataMember]
    public string DM3;
}

and sometimes I want to prevent DM2 from being deserialized when being returned from an OperationContract. Something like this:

[OperationContact]
public MyDC GetMyDC()
{
    MyDC mdc = new MyDC();

    if (condition)
    {
        // Code to prevent DM2 from being deserialized  
    }

    return mdc;
}

I could always make a new DataContract that has only DM1 and DM3 and generate that from the MyDC instance but I want to see if it is possible to programatically remove DM2. Is it possible? How?


Solution

  • [DataContract]
    class MyDC 
    {
        [DataMember]
        public string DM1;
    
        public string DM2;
    
        public bool IsDM2Serializable;
    
        [DataMember(Name="DM2", EmitDefaultValue = false)]
        public string DM2SerializedConditionally
        {
            get
            {
                if(IsDM2Serializable)
                    return null;
                return DM2;
            }
            set { DM2=value; }
        }
    
        [DataMember]
        public string DM3;
    }
    

    Then set IsDM2Serializable to false when you need to hide it:

    [OperationContact]
    public MyDC GetMyDC()
    {
        MyDC mdc = new MyDC();
    
        if (condition)
        {
            // Code to prevent DM2 from being serialized  
            mdc.IsDM2Serializable = false;
        }
    
        return mdc;
    }