Search code examples
c#xmlwcfserialization

How to conditionally avoid property from serializing in WCF?


Is it possible to dynamically avoid property from serializing? Let's say I have got such a metod in my WCF Service:

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
    return new CompositeType();
}

Where CompositeType looks like this:

[DataContract]
public class CompositeType
{
    public bool _flag = true;

    [DataMember]
    public decimal? Value { get; set; }
}

When I invoke GetDataUsingDataContract methods, I'm returning CompositeType object, which is then serializing to XML by the WCF technology. Is it possible to avoid Value property from serializing if the _flag = true?

I read about the [XmlIgnore], [IgnoreDataMember] etc., but what I understand this will always ignore property from serializing, I have to ignore only if flag = true. If flag = false I still want to serialize this property.


Solution

  • If I've understood your requirement, the following should work. The property ValueIfFlagTrue is for serialization only, name it as you wish. You haven't said how you want to handle deserializing, so I've made a guess in the implementation: adjust as needed.

    [DataContract]
    public class CompositeType
    {
        public bool _flag = true;
    
        public decimal? Value { get; set; }
    
        [DataMember(Name = "Value", EmitDefaultValue = false)]
        private decimal? ValueIfFlagTrue
        {
            get
            {
                return _flag ? Value : null;
            }
            set
            {
                _flag = value.HasValue ? true : false;
                Value = value;
            }
        }
    }
    

    UPDATED

    You can put the DataMember attribute on a private property, so there's no need to expose the ValueIfFlagTrue property publicly.