Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created October 21, 2015 11:39
Show Gist options
  • Save hanssens/3b79132106615e244b51 to your computer and use it in GitHub Desktop.
Save hanssens/3b79132106615e244b51 to your computer and use it in GitHub Desktop.
The Nullable Question
// consider the following model
var person = new {
Name = "Harry Potter",
DateOfBirth = DateTime.Now,
DateOfBirthSpecified = true
};
// now if the 'DateOfBirth' is specified, use it's value
// otherwise, simply use null
DateTime? x = (person.DateOfBirthSpecified) ? person.DateOfBirth : null;
// solution #1 (set to null by default, and replace it if condition matches)
DateTime? x = null;
if (person.DateOfBirthSpecified) x = person.DateOfBirth;
// solution #2 (notice the cast at the end)
DateTime? x = (person.DateOfBirthSpecified) ? person.DateOfBirth : (DateTime?)null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment