I am trying to learn use the null conditional operator but can't seem to get it to work,
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u].Value.ToShortDateString() ?? "Empty";
DateIn
is a list of nullable DateTime
(List<Datetime?>
) .
I did debugging and all the values in DateIn[u]
give null.
What am I doing wrong?
If all the values in the DateIn
array are null
, your code would throw a NullReferenceException
.
You may use the null-propagation-operator here:
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u]?.ToShortDateString() ?? "Empty";
This operator (?.
) now returns a nullable string. If DateIn[u]
has a value, ToShortDateString()
is called and the operator returns a nullable string with the returned value.
If DateIn[u]
is null
the operator returns null
, too.
You have a mistake. First check for null
values by HasValue
and use single ?
not double ??
like the following snippet:
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u].HasValue ? DOInfolist[i].RentalItem.SimCard.DateIn[u].ToShortDateString() : "Empty";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With