Reputation: 1426
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.
Upvotes: 3
Views: 213
Reputation: 1426
The stack trace was reporting a wrong line number, causing me to believe the LINQ query was causing the exception. In reality, the exception was being thrown within the foreach loop, a few lines down, where I try to access an object within a Ticket
's properties, which was null.
Lesson learned, don't always believe in and rely on the stack trace entirely!
Upvotes: 1