Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value in a DataContract?

Tags:

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; } 
like image 704
acadia Avatar asked Jul 01 '10 17:07

acadia


People also ask

What is DataContract and DataMember in C#?

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.

What is EmitDefaultValue?

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.

What is DataContract attribute?

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

Is DataContract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.


2 Answers

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.

like image 63
Dan Bryant Avatar answered Oct 02 '22 19:10

Dan Bryant


If you want it always to default to XeroxScan, why not do something simple like:

[DataMember(EmitDefaultValue = false)] public string ScanDevice= "XeroxScan"; 
like image 31
Ta01 Avatar answered Oct 02 '22 19:10

Ta01