The database allows null values for numbers and dates but these data types are not allowed to be null in .NET objects. In times past, a work around might have been to use a value that is unlikely to be used for real cases. For instance, DateTime.MinValue. This solution does not work for a bool data type.
The solution is to use a Nullable (?) data type. Listed below are three properties that are all nullable data types.
public DateTime? ConfirmationDate { get; set; }
public decimal? PledgeAmount { get; set; }
public bool? AmericanCitizen { get; set; }
There are two equivalent was to check if the nullable type has data.
if (myTest.ConfirmationDate.HasValue)
{
// Do Something
}
if (myTest.ConfirmationDate != null)
{
// Do Something
}
Sometimes a value is required for display purposes even when the value is null. You can use the short hand notation with the coalescing operator (??). The two snippets of code below are equivalent.
decimal realNumber1 = myTest.PledgeAmount ?? 0;
decimal realNumber2 = 0;
if (myTest.PledgeAmount != null)
realNumber2 = myTest.PledgeAmount.Value;