I have two dates: LastUpdatedOn
and CreatedBy
. If LastUpdatedOn
has a value then I want to use that value. Otherwise I should use CreatedBy
. If neither LastUpdatedOn
or Createdby
have a value then use Date.MinValue
.
In the code below, CreatedBy
is always used even though LastUpdatedOn
has a value.
var LastUpdated = discrepancy.LastUpdatedOn.HasValue ? discrepancy.CreatedOn.Value.LocalDateTime : DateTime.MinValue;
What is wrong with my code?
CodePudding user response:
You can try this:
var LastUpdated = discrepancy.LastUpdatedOn ?? discrepancy.CreatedOn ?? DateTime.MinValue;
or this:
CodePudding user response:
You are using a ternary operator with discrepancy.LastUpdatedOn.HasValue
as your condition. LastUpdatedOn
is never being assigned to LastUpdated
.
Your code is the same as this:
DateTime LastUpdated;
if (discrepancy.LastUpdatedOn.HasValue)
{
LastUpdated = discrepancy.CreatedOn.Value.LocalDateTime
}
else
{
LastUpdated = DateTime.MinValue;
}
CodePudding user response:
Your description involves two "if"s:
- If LastUpdatedOn is there
- If CreatedOn is there
Hence, if you want to use ternary operator, there should be two of them as well:
var LastUpdated = discrepancy.LastUpdatedOn.HasValue ? discrepancy.LastUpdatedOn : (discrepancy.CreatedOn.HasValue ? discrepancy.CreatedOn : DateTime.MinValue);