For with DateTime in Razor giving out of memory exception

0

I'm having the error out of memory, being caused by this Razor code in my cshtml file, and I can not identify where the problem is.

@for(DateTime data = DateTime.Today.Date; data <= DateTime.Today.AddDays(7).Date; data.AddDays(1))
{
    @data
}
    
asked by anonymous 25.01.2018 / 23:41

1 answer

3

According to the documentation, the DateTime.AddDays

  

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

Notice the emphasis. This method returns the result, and does not modify the instance. Therefore, its data variable is never being modified, generating an infinite loop and hence the OutOfMemory exception.

To solve, just 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 in .NET fiddle

    
26.01.2018 / 00:13