.net-3.5datamembernetdatacontractserializer

Selective serialization with NetDataContractSerializer


Serializing this class works fine. However, sometimes I'd like to exclude the field. Is this possible?

[DataContract]
class Foo
{
    [DataMember]
    Foo _Foo;
}

Setting the field to null temporarily is impossible.


Solution

  • In case someone stumbles upon the same issue, I'll show the solution I went by.

    The idea is to facade the original field like this:

    [DataContract]
    class Foo
    {
        Foo _FooOriginal;
    
        [DataMember]
        Foo _Foo {
            get {
                return whatever ? _FooOriginal : null;
            }
            set {
                _FooOriginal = value;
            }
        }
    }