Created
October 21, 2015 11:39
-
-
Save hanssens/3b79132106615e244b51 to your computer and use it in GitHub Desktop.
The Nullable Question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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