0

I wanna use a #if statement to skip serializing val when val2 is true and to serialize val when val2 is false. But my code seems not to work:

#if val2
    [XmlIgnore]
#else   
    [XmlElement(ElementName = "val")]
#endif
public bool val
{
    { get; set; } = false;
}

[XmlElement(ElementName = "val2")]
public bool val2
{
    { get; set; } = true;
}

What do I have to do to get it working? Thanks

2 Answers2

1

I think you need to define the symbol you are testing with #define. These are pre-processor directives and you cannot use normal property names etc as those come into play during compilation which happens after pre-processing.

This is from the standard:

Evaluation of a pre-processing expression always yields a boolean value. The rules of evaluation for a pre-processing expression are the same as those for a constant expression (§7.19), except that the only user-defined entities that can be referenced are conditional compilation symbols.

As pointed out in this question, you need something like this:

public class Item
{
    public bool val { get; set; }

    public bool ShouldSerializeval()
    {
       return !val2;
    }

    [XmlElement(ElementName = "val2")]
    public bool val2 { get; set; }  
}

void Main()
{
    Item item = new Item(){val=true, val2=true};

    XmlSerializer xs = new XmlSerializer(typeof(Item));
    StringWriter sw = new StringWriter();
    xs.Serialize(sw, item);
    sw.ToString();
}
Community
  • 1
  • 1
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
0

Just add one of the following to your code, and val won't be serialized, when val2 is true:

public bool ShouldSerializeval()
{
    return val2 == false;
}

or

public bool ShouldSerializeval()
{
    return !val2;
}
cramopy
  • 3,459
  • 6
  • 28
  • 42