Search code examples
c#datetimewhile-loopstack-overflow

How to write this function properly? It gives me out of memory every time


I have some code running in my While loop:

while (Time <= EndPeriod)
{
      ... code ...

      Tine.AddTime(Time);
}

The problem I am having is where Time.AddTime(Time) executes it creates a memory leak. The AddTime function checks a class property and adds time via the correct method (e.g. AddDays, AddMonths, etc...) based on the DateFormat variable in a switch. If I put the switch into the loop everything is fine, however if I try to reference this function it does a stack overflow.

My AddTime function is below:

protected DateTime AddTime(DateTime Time)
{
    DateTime myTime = Time;
    switch (DatePart) {
        case "yy":
            myTime.AddYears(1);
            break;
        case "qq":
            myTime.AddDays(1);
            break;
        case "mm":
            myTime.AddMonths(1);
            break;
        case "dd":
            myTime.AddDays(1);
            break;
        case "hh":
            myTime.AddHours(1);
            break;
        case "ss":
            myTime.AddSeconds(1);
            break;
        default:
            myTime.AddMinutes(1);
            break;
    }
    return myTime;
}

What could I be doing wrong?

Thanks


Solution

  • You should change:

    myTime.AddSeconds(1);
    

    to

    // The same for all other methods which considered to modify 
    // a DateTime value including your custom AddTime() method
    myTime = myTime.AddSeconds(1);
    

    In this way condition a value of Time would be changes so you have a chance that condition (Time <= EndPeriod) will be passed ever.

    All methods like DateTime.AddYears() DateTime.AddDays() does not modify a value of object itself but returns new value.

    MSDN:

    This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation.