I have a DateTime?
variable, sometimes the value is null
, how can I return an empty string \"\"
when the value is null
or
Calling .ToString()
on a Nullable<T>
that is null
will return an empty string.
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
if (aDate.HasValue)
return aDate;
else
return string.Empty;
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
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>