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";
Share:
16,565
acadia
Author by

acadia

Updated on June 06, 2022

Comments

  • acadia
    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
    acadia about 14 years
    Thanks Dan. I have a question. The default value will be XeroxScan but if a user passes HPScan it will take HPScan right?
  • Dan Bryant
    Dan Bryant about 14 years
    Do 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
    xr280xr over 12 years
    I tried this but it doesn't seem to be working. Isn't OnDeserializing only used with binary serialization?
  • Dan Bryant
    Dan Bryant over 12 years
    @xr280xr, what serializer are you using? These particular attributes are for use by the DataContractSerializer.
  • xr280xr
    xr280xr over 12 years
    The 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
    ajaysinghdav10d about 8 years
    Hi 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
    user1496062 about 8 years
    Its fine for the type defaults and for others just set in the constructor far more elegant IMHO