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?
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 ...