For with Datetime in Razor giving out of memory Exception

Asked

Viewed 23 times

0

I am having out of memory error, being it caused by this Razor code in my cshtml file, and can’t identify where the problem is.

@for(DateTime data = DateTime.Today.Date; data <= DateTime.Today.AddDays(7).Date; data.AddDays(1))
{
    @data
}
  • I find it unlikely, the problem must be elsewhere.

1 answer

2


According to the documentation, the method DateTime.AddDays

Returns a new DateTime adding the specified number of days to the value of that instance.

Note the emphasis. This method returns the result, and does not modify the instance. Therefore, its variable data is never being modified, generating a loop infinite and, consequently, the exception Outofmemory.

To resolve, simply overwrite data with the return value of the method

@for(DateTime data = DateTime.Today.Date; data <= DateTime.Today.AddDays(7).Date; data = data.AddDays(1))
{
    @data
}

See working on . NET fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.