2

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...

5 Answers 5

9

Using the conditional operator:

vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
                                  string.Empty;
Sign up to request clarification or add additional context in comments.

11 Comments

@MichaelPaulukonis - Pretty much.
No, if else are both blocks and this is an expression
@Oded "What happens if PrDateTime is null?" The same question applies to your code right now as well
@Esailija - an if/else can be constructed without braces, and the IL that would be generated between the two is so similar tas to be considered identical.
@MatthewCox - No, it doesn't. PrDateTime is a DateTime? - HasValue will either be true or false.
|
5

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);

1 Comment

There's an if..else in there, but this seems to be the fastest way (reusable) to do it.
2
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.

Comments

2
return (i.PrDateTime.Value ?? string.Empty).ToString();

Just tested and it seems to work.

Comments

-1
return i.PrDateTime.Value.ToString("s") ?? string.Empty;

1 Comment

to be clear it fails if i.PrDateTime.Value is null, not i.PrDataTime, but I don't even understand this syntax...how can ToString("s") ever return a null..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.