Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
like image 642
gyosifov Avatar asked Dec 24 '22 23:12

gyosifov


1 Answers

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();
like image 150
André Snede Avatar answered Jan 01 '23 03:01

André Snede