tags:

views:

30

answers:

2

Hello,

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; }
+2  A: 

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.

Dan Bryant
Thanks Dan. I have a question. The default value will be XeroxScan but if a user passes HPScan it will take HPScan right?
acadia
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.
Dan Bryant
A: 

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

[DataMember(EmitDefaultValue = false)]
public string ScanDevice= "XeroxScan";
RandomNoob