C# Nullable to string

后端 未结 11 1868
挽巷
挽巷 2020-12-16 09:29

I have a DateTime? variable, sometimes the value is null, how can I return an empty string \"\" when the value is null or

相关标签:
11条回答
  • 2020-12-16 09:52

    Calling .ToString() on a Nullable<T> that is null will return an empty string.

    0 讨论(0)
  • 2020-12-16 09:53
    DateTime d?;
    string s = d.HasValue ? d.ToString() : string.Empty;
    
    0 讨论(0)
  • 2020-12-16 09:56
    if (aDate.HasValue)
        return aDate;
    else
        return string.Empty;
    
    0 讨论(0)
  • 2020-12-16 09:59
    DateTime? MyNullableDT;
    ....
    if (MyNullableDT.HasValue)
    {
        return MyNullableDT.Value.ToString();
    }
    return "";
    
    0 讨论(0)
  • 2020-12-16 10:02
    DateTime? d;
    // stuff manipulating d;
    return d != null ? d.Value.ToString() : String.Empty;
    
    0 讨论(0)
  • 2020-12-16 10:03

    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>
    
    0 讨论(0)
提交回复
热议问题