The object i is from database. PrDT is a string, PrDateTime is DataTimeOffset type, nullable
vi.PrDT = i.PrDateTime.Value.ToString("s");
What is the quick way? I don't want if else etc...
Using the conditional operator:
vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
string.Empty;
PrDateTime is a DateTime? - HasValue will either be true or false.You can do an extensions method:
public static class NullableToStringExtensions
{
public static string ToString<T>(this T? value, string format, string coalesce = null)
where T : struct, IFormattable
{
if (value == null)
{
return coalesce;
}
else
{
return value.Value.ToString(format, null);
}
}
}
and then:
vi.PrDT = i.PrDateTime.ToString("s", string.Empty);
string.Format("{0:s}", i.PrDateTime)
The above will return back an empty string if it's null. Since Nullable<T>.ToString checks for a null value and returns an empty string if it is, otherwise returns a string representation (but can't use formatting specifiers). Trick is to use string.Format, which allows you to use the format specifier you want (in this case, s) and still get the Nullable<T>.ToString behavior.
return i.PrDateTime.Value.ToString("s") ?? string.Empty;
i.PrDateTime.Value is null, not i.PrDataTime, but I don't even understand this syntax...how can ToString("s") ever return a null..