Reputation: 81292
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
?
Upvotes: 37
Views: 33523
Reputation: 162
As Eric Lippert's answer. I think this will This code should meet the requirements.
Nullable<DateTime> nullableDatetime = null;
string? datetimeString = nullableDatetime.ToString();
string nullableString = datetimeString ?? string.Empty;
Upvotes: 0
Reputation: 39
According to Microsoft's documentation:
The text representation of the value of the current Nullable object if the HasValue property is true, or an empty string ("") if the HasValue property is false.
Upvotes: 0
Reputation: 6836
All you need to do is to just simply call .ToString()
. It handles Nullable<T>
object for null
value.
Here is the source of .NET Framework for Nullable<T>.ToString()
:
public override string ToString() {
return hasValue ? value.ToString() : "";
}
Upvotes: 3
Reputation: 1025
Calling .ToString()
on a Nullable<T>
that is null
will return an empty string.
Upvotes: 8
Reputation: 1220
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
Upvotes: 1
Reputation: 12401
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
Upvotes: 43
Reputation: 660128
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.
Upvotes: 113
Reputation: 354556
Actually, this is the default behaviour for Nullable types, that without a value they return nothing:
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
this yields
<>
<2009-09-18 19:16:09>
Upvotes: 18
Reputation: 754763
You could write an extension method
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
Upvotes: 7
Reputation: 140823
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
Upvotes: 1
Reputation: 4992
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
Upvotes: 2