C# Nullable to string

后端 未结 11 1869
挽巷
挽巷 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 10:04
    string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
    0 讨论(0)
  • 2020-12-16 10:04

    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.

    0 讨论(0)
  • 2020-12-16 10:07

    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.

    0 讨论(0)
  • 2020-12-16 10:11

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