Monday, March 26, 2012

Why oh Why? IIf(...)

Why does the following code gives me a System.IndexOutOfRangeException, while he shouldn't evaluate the correctness of the true part?


Dim myRow As DataRow
Dim myApprovals As DataTable

myApprovals = DBCom.GetApprovalsForReport(...)
myRow = IIf(myApprovals.Rows.Count > 0, myApprovals.Rows(0), Nothing)

If myApprovals contains a row, there isn't a problem. The IIf expression evaluates True and myRow becomes myApprovals.Rows(0). The problem arises when myApprovals.Rows.Count = 0 and the IIf expressions evaluates False. When that happens he still checks the correctness of the true part, myApprovals.Rows(0), which offcourse gives an IndexOutOfRangeException. But why does he do that? Why doesn't he just assigns the false part, Nothing, to myRow?

All help appriciatedcheck out this article:Use And and Or Accurately With VB.NET

0 comments:

Post a Comment