I have a WCF data contract with a bunch of properties of primitive types like int and decimal, and DateTime
(which is, of course, a struct).
My co-worker suggested making them all nullable and then validating required values on the service end by checking for null. I believe part of the reasoning is that since it is a serializable object, you can't enforce required values with a constructor on the data contract - and it avoids the headache of testing for default values.
However, I would also like required properties to be implicit in the contract so a client can have some idea what properties are required.
So instead of doing something like,
[DataMember]
public Nullable<int> AgencyID { get; set; }
which would allow me to cleanly test for null on the service end, I'd do this:
[DataMember(IsRequired = true, EmitDefaultValue = true)]
public int AgencyID { get; set; }
It is my understanding that this will throw an exception if the property hasn't been assigned a value or has a default value of 0 - which is the desired behavior. Is this the best practice for enforcing required properties on the client side? Is there any advantage to just making everything nullable and checking it on the service end instead?
I don't think its a good approach to make all of them Nullable because then client won't know by your contract that if a field is really required or not.
If you apply IsRequired=true
then it's mandatory to provide field value else it would throw exception but this approach is relatively better than Nullable one...
In many scenarios I have used DTOs (Data Transfer Objects) for different services... having required fields...