IndexOutOfRangeException occured due to an if condition

An IndexOutOfRangeException just triggered in a little project I'm building, but why?

Here's the boolean condition:

(messages != null && messages.Rows[0] != null)

What I was trying to do is to check if these two objects were initialized, but as you already figured this happened all of a sudden.

Jon Skeet
people
quotationmark

It sounds like you need to check whether or not Rows is empty too. We don't actually know the type of Rows, but you might want:

if (messages != null && messages.Rows.Count > 0 && messages.Rows[0] != null)

Or you could use LINQ to get the first row if it exists, and check whether that's null:

if (messages != null && messages.Rows.FirstOrDefault() != null)

(That's assuming Rows implements IEnumerable<T> for some T.)

It's also possibly that Rows[0] will never be null, and you really only need to check whether the count is greater than 0:

if (messages != null && messages.Rows.Count > 0)

Or:

if (messages != null && messages.Rows.Any())

people

See more on this question at Stackoverflow