1

I've been playing around with serializing objects and I'm wondering whether you can use the DataMember attribute to overwrite the serialized value based on a condition? For instance if I had this property on my class:

[DataMember]
public string Foo { get; set; }

and I create an instance of my class where Foo is set to IsFoo, would it be possible for me to use the DataMember attribute to serialize it into something like this:

<Foo>Bar</Foo>

Note that this is a hypothetical question and that in real life this would surely be bad practice or a data-issue, but is it possible at all?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stig Perez
  • 3,595
  • 4
  • 23
  • 36

1 Answers1

1

No you cannot do that.

The [DataMember] attribute only tells the WCF DataContractSerializer to include that value (in the property) into the WCF message - it doesn't allow you to alter the value in the process....

If you need to have Bar in the WCF message, then you must set Foo = "Bar"; in your code ...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I think you're right it probably won't make much sense to expect the DataMember attribute to act that way. ...and thanks for the editorial tips as well :-) – Stig Perez Mar 21 '15 at 13:46