user2277362
user2277362

Reputation: 113

Problems with date time and infinite loops

I know there probably is a really an obvious answer to this question but why am I getting an infinite loop with this code? (laterDate1 is later date than dateTime1 and laterDate2 is a later date than dateTime2)

while (dateTime1.CompareTo(laterDate1) <= 0)
        {
            DateTime dateTime2 = otherDateTime;
            while (dateTime2.CompareTo(laterDate2) <= 0)
            {
                dateTime2.AddDays(1);
            }
            dateTime1.AddDays(1);
        }

Thanks in advance for your help. (My brain is not working today)

Upvotes: 0

Views: 151

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

dateTime1.AddDays(1); does not modify dateTime1. It returns new DateTime instance. You have to assign it back to your variable:

dateTime1 = dateTime1.AddDays(1);

The same applies to dateTime2.AddDays(2):

dateTime2 = dateTime2.AddDays(1);

btw, DateTime is a struct and is immutable, so every state-changing method returns new instance, instead of modifying the one you're calling it on. You should remember about that while working with DateTime.

Upvotes: 7

Related Questions