2

I'm trying to communicate with a system (using xml) that requires certain optional fields depending on the value of another field. If I send an unneeded one, the system returns an error.

I am using ShouldSerialize for this situation but I still have so many fields and types.

Is there an easy way to do this or is this the wrong way to go about this? What should I use? I am writing so much duplicated code and this feels wrong.

[Serializable()]
public class AEntity
{
    public int Id { get; set; }
    public int All1 { get; set; }
    public int All2 { get; set; }
    public int All3 { get; set; }


    public bool ShouldSerializeTypeBField1 => CommandControls.IfBNeeded(Id);
    public int TypeBField1 { get; set; }

    public bool ShouldSerializeTypeBField2 => CommandControls.IfBNeeded(Id);
    public int TypeBField2 { get; set; }

    public bool ShouldSerializeTypeBField3 => CommandControls.IfBNeeded(Id);
    public int TypeBField3 { get; set; }
    ...

    public bool ShouldSerializeTypeCField1 => CommandControls.IfCNeeded(Id);
    public int TypeCField1 { get; set; }

    public bool ShouldSerializeTypeCField2 => CommandControls.IfCNeeded(Id);
    public int TypeCField2 { get; set; }

    public bool ShouldSerializeTypeCField3 => CommandControls.IfCNeeded(Id);
    public int TypeCField3 { get; set; }
    ...


}

I would like to write something like this

public bool ShouldSerializeTypeBFields => CommandControls.IfBNeeded(Id);
public bool ShouldSerializeTypeCFields => CommandControls.IfCNeeded(Id);

Note: Field names don't actually start with TypeBField; that's a placeholder for a normal field name like Phone, Address, etc.

Eric MSFT
  • 3,246
  • 1
  • 18
  • 28
Abdullah
  • 627
  • 9
  • 27
  • Serialize will only serialize public properties so if you do not want to serialize a property remove the public attribute. – jdweng Jul 18 '19 at 06:22
  • 1
    I feel your pain. Other options include the [*Specified pattern](https://stackoverflow.com/q/37838640/3744182) which is no easier, and implementing `IXmlSerializable`, which is far worse. Json.NET has the ability to customize the logic of its contract resolver, but `XmlSerializer` does not allow this. – dbc Jul 18 '19 at 08:59
  • One cleaner option I can think of would be to use `ElementSkippingXmlTextWriter` from [this answer](https://stackoverflow.com/a/32150990/3744182) to [Custom xmlWriter to skip a certain element?](https://stackoverflow.com/q/32149676/3744182) to filter unwanted elements by name as they are being written. Or if you only need to serialize and not deserialize, you could do some custom serialization logic inside an `[XmlAnyElement]` property as shown in [this answer](https://stackoverflow.com/a/33180709) to [Better IXmlSerializable format?](https://stackoverflow.com/q/33163580). – dbc Jul 18 '19 at 09:02

0 Answers0