views:

152

answers:

1

I've got the following LINQ Statement:

Dim PSNum As Integer = 66 
Dim InvSeq = (From invRecord In InvSeqDataSet.RptInvSeqDT.AsQueryable() _
                Where IIf(invRecord.IsPack_NumNull(), False, invRecord.Pack_Num = PSNum) _
                Select New With _
                {.Inv = invRecord.Invoice_Num, .Seq = invRecord.Inv_Seq}).FirstOrDefault()

invRecord.Pack_Num is a field of type Integer. This means that when I try to access it, if it is DBNull I get a StronglyTypedException. The above code throws this exception. If, however, I remove the "invRecord.Pack_Num = PSNum" and in its place put something like "True", the code works fine.

So I guess my question is, why is that that invRecord.IsPack_NumNull() returns False when the value is in fact DBNull and what can I use as a conditional instead? I've been beating my head against the wall for a while now and I can't find a solution to this problem.

+1  A: 

In VB.NET, IIf() evaluates every one of its arguments since it's a function, not a language statement. So inv.Record.Pack_Num = PSNum will always be evaluated.

You can use If() instead of IIf() (same syntax) which uses short-circuiting evaluation so everything will work as expected.

On a side node, be careful with And and Or which have the same behavior. Use AndAlso and OrElse instead if you need short-circuiting evaluation.

Julien Lebosquain
Yup, you were right. I'm not sure how I missed this but I thought it was the other way around. Intuitively, I always thought IIf meant something like "If and only If" which would imply that "short-circuit" behavior that I was going for. Anyway, many thanks.
Overhed
I guess that the VB language team intended it to mean "inline if".
Christian Hayter