Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Null Conditional Operator with nullable datetime

Tags:

c#

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?

like image 621
Bloopie Bloops Avatar asked Feb 06 '23 00:02

Bloopie Bloops


2 Answers

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.

like image 154
René Vogt Avatar answered Feb 08 '23 17:02

René Vogt


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";
like image 37
Afnan Ahmad Avatar answered Feb 08 '23 15:02

Afnan Ahmad