I have a Windows Service with a log file to write any exceptions caught. In a simple foreach using LINQ, I am getting an exception for the classic:
Object reference not set to an instance of an object.
However, when I run the code locally, by 'freezing' the Windows Service code and just running the code through a Main function, I can't seem to replicate this issue. The stack trace says the line causing the issue is 142.
var newTickets = tickets
.Where(t => t != null)
.Where(t => (DateTime)t.LastActivityDate >= lastAutoTaskSync);
foreach(Ticket ticket in newTickets) //Line 142
Strangely, I have checked everything possible I could think it could be, by adding the following lines:
var newTickets = tickets
.Where(t => t != null)
.Where(t => (DateTime)t.LastActivityDate >= lastAutoTaskSync);
if (newTickets == null) throw new Exception("newTickets is null");
if (tickets == null) throw new Exception("tickets is null");
if (lastAutoTaskSync == null) throw new Exception("date is null");
foreach (Ticket ticket in newTickets)
And again, the same line throws the same exception.
Is there anything that I may be missing, or something that could cause this exception? I thought it may be the code inside the LINQ, such as LastActivityDate being null, but if that were the case, surely this would be the line to throw the exception, not the foreach itself?
To add, the code runs around 50% of the time, running through the foreach with no issues. For example, the service log indicates that the code in the loop runs 3 or 4 times, and then the exception hits on the fifth.
t.LastActivityDateisnullin the first element of the array. You could check this by adding a.ToList()tovar newTicketsand see if the error moves there.LastActivityDateis a nullable DateTime and some are null he'd get aSystem.InvalidOperationExceptioninstead on the cast toDateTime.tickets? Is this anIQueryablethat itself executes some other lambdas that may cause the exception?objecttype. I have added a.ToList()and have put it back on the test server. It may be worth noting that this code runs half the time with no issues and performs the functions coded into it.