Is the DataMember IsRequired attribute in combination with a Nullable type contradictory?
Asked Answered
F

2

15

I came across this today in a WCF contract:

[DataMember(IsRequired = true)]
public DateTime? LastModified { get; set; } 

What are the consequences of IsRequired = True and a nullable DateTime? They appear to be contradictory to each other.

Flannery answered 14/10, 2011 at 11:10 Comment(0)
B
8

It can make sense if you want to initialize it with null and let user to set a valid date. So before submitting it can validate user input.

Here is a similar contradictory that may answer your question.

Interaction with IsRequired

The DataMemberAttribute attribute has an IsRequired property (the default is false). The property indicates whether a given data member must be present in the serialized data when it is being deserialized. If IsRequired is set to true, (which indicates that a value must be present) and EmitDefaultValue is set to false (indicating that the value must not be present if it is set to its default value), default values for this data member cannot be serialized because the results would be contradictory. If such a data member is set to its default value (usually null or zero) and a serialization is attempted, a SerializationException is thrown.

Brutify answered 14/10, 2011 at 11:40 Comment(3)
So, if I understand you correctly (or more appropriately - MSDN double-Dutch), a SerializationException would be the result if the value of this property is set to null OR excluded completely. Thus it would be better to exclude the IsRequired property altogether?Flannery
Think about compatibility with older versions of your service. If you want you can make new members IsRequired false and pass a default value in.Swaddle
@Junto: I think so, IsRequired false is safer and makes more sense.Brutify
S
3

A guess: you MUST have a node for 'LastModified' (=required) but the contents can be empty (=value is null).

Slake answered 14/10, 2011 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.