Reputation:
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...
Upvotes: 2
Views: 5701
Reputation: 571
return (i.PrDateTime.Value ?? string.Empty).ToString();
Just tested and it seems to work.
Upvotes: 2
Reputation: 3892
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.
Upvotes: 2
Reputation: 37719
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);
Upvotes: 5
Reputation: 498972
Using the conditional operator:
vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
string.Empty;
Upvotes: 9