acadia
acadia

Reputation: 2333

Set default value in a DataContract?

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; }

Upvotes: 21

Views: 17526

Answers (2)

Ta01
Ta01

Reputation: 31630

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

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

Upvotes: 6

Dan Bryant
Dan Bryant

Reputation: 27515

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.

Upvotes: 35

Related Questions