I have a DateTime?
variable, sometimes the value is null
, how can I return an empty string \"\"
when the value is null
or
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
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.
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.
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();
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() : "";
}