Is there any way to conditionally specify EmitDefaultValue at runtime for the DataContractSerializer in .NET? Are there any workarounds?
For example, I am curious whether I could use EmitDefaultValue=false for WCF serialization, but I would like to be able to use EmitDefaultValue=true for XMLs generated for external interfaces, such as print.
Well, two options you potentially have are to use a data contract surrogate or an IObjectReference. I think both of these are overkill for you, but if you really, really want to support this scenario on your end, maybe this is a sacrifice you’re willing to make. Note that using them also has significant implications for performance, interoperability, exposure via schema, etc.
I also want to point out that what you’re trying to do — EmitDefaultValue of false — is not recommended for a number of reasons, even though I know what the common motivations are. See Why is using [DataMember(EmitDefaultValue = false)] not recommended?