Set default value in a DataContract?
16,565
Solution 1
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.
Solution 2
If you want it always to default to XeroxScan, why not do something simple like:
[DataMember(EmitDefaultValue = false)]
public string ScanDevice= "XeroxScan";
Author by
acadia
Updated on June 06, 2022Comments
-
acadia about 2 years
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; }
-
acadia about 14 yearsThanks Dan. I have a question. The default value will be XeroxScan but if a user passes HPScan it will take HPScan right?
-
Dan Bryant about 14 yearsDo you mean if they pass a device into the constructor? If so, yes, you can set the property in the constructor after you call SetDefaults and it will use the new value. If you mean when the data is deserialized, that will work as well, since OnDeserializing is called before deserializing occurs. This way you can set all of your initial 'default' state before your properties are populated during deserialization.
-
xr280xr over 12 yearsI tried this but it doesn't seem to be working. Isn't OnDeserializing only used with binary serialization?
-
Dan Bryant over 12 years@xr280xr, what serializer are you using? These particular attributes are for use by the DataContractSerializer.
-
xr280xr over 12 yearsThe same. Nevermind, it's working as it should, just not how I wanted. I think what I want is to add EmitDefaultValue so that if the client doesn't specify a value, the default on the server will hold. As I had it, I think the client's .NET default was overwriting the default the server set when deserializing.
-
ajaysinghdav10d about 8 yearsHi kd7, your solution works only if we are using the DataContract at the service side but for incoming requests where this DataContract is being passed as an argument, this does not work. As an alternate solution we must create two Properties [One Normal and One Nullable] in the DataContract and expose a nullable type as a DataMember and set the values from the exposed field to the Non-Exposed field.
-
user1496062 about 8 yearsIts fine for the type defaults and for others just set in the constructor far more elegant IMHO