How can I set a default value to a DataMember for example for the one shown below:
I want to set ScanDevice="XeroxScan" by default
[DataMember] public string ScanDevice { get; set; }
A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.
EmitDefaultValue. DataMember EmitDefaultValue is a Boolean attribute with the default value of true. If the value is not provided for DataMember then the corresponding default value will be set to the member for example integer it will be set as 0, for bool it is false, any reference type is null.
[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.
No, the DataContractAttribute is not required - WCF will infer serialization rules.
I've usually done this with a pattern like this:
[DataContract] public class MyClass { [DataMember] public string ScanDevice { get; set; } public MyClass() { SetDefaults(); } [OnDeserializing] private void OnDeserializing(StreamingContext context) { SetDefaults(); } private void SetDefaults() { ScanDevice = "XeroxScan"; } }
Don't forget the OnDeserializing, as your constructor will not be called during deserialization.
If you want it always to default to XeroxScan, why not do something simple like:
[DataMember(EmitDefaultValue = false)] public string ScanDevice= "XeroxScan";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With