Set default value in a DataContract?
Asked Answered
D

2

21

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; }
Deepseated answered 1/7, 2010 at 17:16 Comment(0)
B
35

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.

Boden answered 1/7, 2010 at 17:18 Comment(5)
Thanks Dan. I have a question. The default value will be XeroxScan but if a user passes HPScan it will take HPScan right?Deepseated
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.Boden
I tried this but it doesn't seem to be working. Isn't OnDeserializing only used with binary serialization?Marshmallow
@xr280xr, what serializer are you using? These particular attributes are for use by the DataContractSerializer.Boden
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.Marshmallow
D
6

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

[DataMember(EmitDefaultValue = false)]
public string ScanDevice= "XeroxScan";
Dunc answered 1/7, 2010 at 17:53 Comment(2)
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.Mcgruder
Its fine for the type defaults and for others just set in the constructor far more elegant IMHOMercurialism

© 2022 - 2024 — McMap. All rights reserved.