Brian J Brian J - 11 months ago 52
C# Question

How to convert a nullable datetime value to string.empty when datetime is null?

I'm reading back a nullable

property then assigning that value to a string property in short date format.

I can convert the date time value to a short date string and assign to the
property. But I'm not sure how to assign a
value to the string if the
is null.

How can you convert a datetime? value to string.empty when datetime? is null?

This is the assignment in linq:

var status_list = query_all.ToList().Select(r => new RelStatus
IT_Date_String = r.IT_Date.Value.ToString("yyyy-MM-dd") != null ? r.IT_Date.Value : null

And the properties in the model:

public DateTime? IT_Date { get; set; }
public string IT_Date_String { get; set; }

Answer Source

You're calling the IT_Date.Value.ToString(...) regardless of whether IT_Date actually has a value.

So you need to turn the expression around:

r.IT_Date.HasValue ? r.IT_Date.Value.ToString(...) : ""

This way ToString() will only be called when IT_Date has a value.

You can also implement this in the getter, as mentioned in a now-deleted comment:

public string IT_Date_String 
        return IT_Date.HasValue ? IT_Date.Value.ToString(...) : "";

This way you won't have to reimplement the logic everywhere you access this model, and as a bonus, it will only be executed when it's actually requested.

There's also no need to explicitly use String.Empty, the string "" will be interned to the same at runtime.