I have a DateTime?
variable, sometimes the value is null
, how can I return an empty string ""
when the value is null
or the DateTime
value when not null
?
Though many of these answers are correct, all of them are needlessly complex. The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null. Just call ToString on your value; it will do exactly what you want.
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.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