1

I use nullable value types a lot when designing classes that have properties which may remain null, i.e. when the object is being persisted. For example:

public int? MyProperty { get; set; }

My question is: should all value-type properties in public (API) POCOs be nullable because it's not known when the consumer will set the values, even in cases where the properties must not be null when the POCO is saved? If not, then there's the risk that the "default" value (e.g. 0 for an int) will accidentally be saved.

  • 0 isn't null. If you can't persist a null as a null, then why use nullables in the first place? – Dan Pichelman Feb 25 '15 at 14:56
  • I know 0 isn't null. The point is the consumer must supply a non-null value before persisting. If the value-type property isn't provided by the consumer when they're filling the POCO, then it will be, e.g. 0 (for int). That's ambiguous because it may be a valid value. – rory.ap Feb 25 '15 at 14:58
  • It's possible to serialize a nullable and keep the null value. See Serialize a nullable int – Dan Pichelman Feb 25 '15 at 15:03
  • I'm not trying to serialize anything. I'm persisting the data in a database. – rory.ap Feb 25 '15 at 15:03
  • 1
    Wouldn't it be better to make the setters private and use a constructor? That way that kind of validation can be done there, and by the time the object is populated, you'll already have guarantees about the data. Not sure how you're doing your database communication, but ORMs should support private setters – Ben Aaronson Feb 25 '15 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.