gyosifov
gyosifov

Reputation: 3223

DateTime? AddDays Extension Method

I want to write an extension method that adds one day to a Nullable DateTime, but modifies the date itself.

I want to use it as follows:

someDate.AddOneDay();

This directly changes the value of someDate.

The code I initially wrote was:

public static DateTime? AddOneDay(this DateTime? date)
{
    if (date.HasValue)
    {
        date.Value = date.Value.AddDays(1);
    }

    return null;
}   

but this doesn't work since the reference is changed thus calling it this way won't change the value of someDate.

Is there a way to achieve this and avoid code like:

someDate = someDate.AddOneDay();

Also I was thinking for some setter of the DateTime properties, but they don't have any..

public int Day { get; }
public int Month { get; }
public int Year { get; }

Upvotes: 4

Views: 2399

Answers (3)

Roman Bezrabotny
Roman Bezrabotny

Reputation: 186

old school %)

public static void AddOneDay(ref DateTime date)
{
    if (date != null) date = date.AddDays(1);
}

usage:

DateTime date = DateTime.Now;
AddOneDay(ref date);

UPD

one line version of method:

public static void AddOneDay(ref DateTime date) { date = date.AddDays(1); }

Upvotes: 3

Kobi
Kobi

Reputation: 138007

C# does support a similar feature, even for mutable values, which is the use of += on nullable values:

DateTime? date = GetDate();
var oneDay = TimeSpan.FromDays(1);
date += oneDay;

Upvotes: 0

André Snede
André Snede

Reputation: 10045

You can't DateTime is immutable, and should stay that way.

Just do:

someDate = someDate.AddOneDay();

And if you want to be more specific, you could rename your function to:

DateTime? someDate = someDate.AddOneDayOrDefault();

Upvotes: 7

Related Questions