2

I have the following:

[DataContract]
public class Foo
{
    [DataMember(EmitDefaultValue = true)
    public bool Bar { get; set; }
}

2 Questions:

  1. What really happens here because my bool can't really be null, so if I emit the default value then what?

  2. How do I make it so that if someone passes a message without the Bar part then it my server sets it to true instead of false by default?


Basically, my bar member is not required to be transmitted over the soap message and if it isn't I want it to default to true, not false. I'm not sure of the proper combination to make my message sizes efficient (cut out anything unnecessary) and then default the value to what I want if it isn't in the message?

michael
  • 14,844
  • 28
  • 89
  • 177
  • 2
    To answer Q1, As Ladislav's example below shows, 'EmitDefaultValue' on a value type really only makes sense for a Nullable. It means that the SOAP message will have a `` element. If SOAP validation is enabled, this would probably generate a validation error if the value type is not Nullable. For complex (object) types, this is not a problem. – mdisibio Jun 06 '11 at 15:11
  • 2
    To answer Q2, I think Ladislav's example is overkill. When you say 'someone passes a message without the Bar', don't forget you have an object model behind the message...so just create a private backing field 'bool bar = true' and so if the `Bar` property is never set, it will default to true when the object is constructed from the SOAP message and the property is queried. – mdisibio Jun 06 '11 at 15:15
  • This originally confused me as well... but remember, you don't really need to use the `EmitDefaultValueAttribute`. Microsoft even states it should only be used in specific cases. Also, keep in mind this is Emit (as in to produce), not Omit (as in to leave out). – myermian Jun 20 '11 at 18:38

1 Answers1

7

EmitDefaultValue is true by default.

You can try to useDefaultValue attribute from System.ComponentModel but I'm not sure if it works.

I just tested DefaultValue attribute and it doesn't work. It means that you cannot change default value - default value of the data type will be always used.

If you want to set your Bar to true use:

[DataContract]
public class Foo
{
    [DataMember(EmitDefaultValue = false)
    public bool? Bar { get; set; }

    [OnDeserialized]
    private void SetValuesOnDeserialized(StreamingContext context)
    {
        if (!Bar.HasValue) 
        {
           Bar = true;
        }
    }
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670