Jack
Jack

Reputation: 4914

Best way to alter nullable type, if not null, but return null if null already

this sort of thing comes up all the time,

this works but is ugly:

DateTime? firstDay = null;
if (Day.HasValue) firstDay = Day.Value.AddDays(-14);

this won't work:

DateTime? firstDay = Day.HasValue ? Day.Value.AddDays(-14) : null;

unless:

DateTime? firstDay = Day.HasValue ? Day.Value.AddDays(-14) : (DateTime?)null;

Maybe there should be another operator!

DateTime? firstDay = Day ??? Day.Value.AddDays(-14);

Upvotes: 1

Views: 484

Answers (3)

to StackOverflow
to StackOverflow

Reputation: 124776

Since all operations on nullable types are null-propagating except concatenation, you could use:

DateTime? Day = ...; 
...
DateTime? firstDay = Day + TimeSpan.FromDays(-14); 

Upvotes: 2

sellmeadog
sellmeadog

Reputation: 7517

What's wrong with:

DateTime? firstDay = Day.HasValue ? Day.Value.Add(-14) : Day;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502796

You could add an extension method to Nullable<T>

public static Nullable<T> TransformIfNotNull<T>(this Nullable<T> value,
                                                Func<T, T> transformer)
    where T : struct
{
    return value == null ? value : transformer(value.Value);
}

Then:

DateTime? firstDay = Day.TransformIfNotNull(x => x.AddDays(-14));

Note that although your version using the null literal doesn't work without casting, you could use:

DateTime? firstDay = Day.HasValue ? Day.Value.AddDays(-14) : Day;

... assuming you know Day won't change type between calls, of course.

Upvotes: 5

Related Questions