tags:

views:

663

answers:

12

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?

A: 
            DateTime? MyNullableDT;
            ....
            if (MyNullableDT.HasValue)
            {
                return MyNullableDT.Value.ToString();
            }
            return "";
Ahmed Khalaf
+25  A: 
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
Jon Seigel
Thank you , exactly what I was looking for
JL
What!? You can just call .ToString() on the Nullable<DateTime> instance to get String.Empty. Even Eric Lippert (who might have even implemented this behavior) notes this. _That_ should be the accepted answer.
codekaizen
@codekaizen - I get an exception when I try that. So no, that would not be the accepted answer. Perhaps this is not a problem in more recent versions of c# or .net?
Kimball Robinson
@k.robinson - perhaps that is because you are using a boxed reference to the instance. Please realize that I'm advocating the same as Eric Lippert - one of the creators of the .Net platform itself - is pointing out in his answer. If you have a problem, you might want to reconsider if "select isn't broken" (http://www.pragprog.com/the-pragmatic-programmer/extracts/tips).
codekaizen
@codekaizen - Ok. I still wish I could do this without a typecast: dateTimeField.Text = dateTimeObj.HasValue ? ((DateTime) dateTimeObj).ToShortDateString() : string.Empty;
Kimball Robinson
+2  A: 
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
Cecil Has a Name
A: 
    if (aDate.HasValue)
        return aDate;
    else
        return string.Empty;
Mike
+1  A: 
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
Daok
+8  A: 

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();
JaredPar
Or better yet: make it generic: `public static string ToSafeString<T>(this T? obj) where T : struct` :)
JulianR
Holy smokes, didn't realize .NET had this ability!
tster
+10  A: 

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>
Joey
+1 Did not know this. However, you cannot supply a formatting string this way.
Jon Seigel
Hm, right. Though this may not be a problem in this case. I didn't know this myself too until yesterday, though. Stumbled over it when looking at `Nullable<T>` in Reflector :-)
Joey
A: 

string date = myVariable.HasValue ? myVariable.ToString() : string.Empty;

Gurdas Nijor
+14  A: 

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.

Eric Lippert
+1  A: 

The shortest possible way is to use this:

Convert.ToString(myVariable);

If it receives null, the result will be an empty string. Otherwise, it will call DateTime.ToString().

Pavel Minaev
A: 

Calling .ToString() returns an empty string for a null value.

DJ
A: 

Always try to avoid using Convert.Toxxxxx. The overhead is massive, especialy when processing a large number of "records".

Barry

Barry Clark