user1108948
user1108948

Reputation:

Return empty string if object null

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

Answers (5)

MalachiteBR
MalachiteBR

Reputation: 571

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

Just tested and it seems to work.

Upvotes: 2

SPFiredrake
SPFiredrake

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

eulerfx
eulerfx

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

Kevin
Kevin

Reputation: 704

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

Upvotes: -1

Oded
Oded

Reputation: 498972

Using the conditional operator:

vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
                                  string.Empty;

Upvotes: 9

Related Questions