3

I'm experiencing unpredicted effects with nullables in VB.net. The object in question has a property defined:

Public Property Value As Int32?

When I try to coalesce the value using IIf, I get a null exception

cmd.Parameters.AddWithValue("@HOValue", IIf(headOffice.Value.HasValue, headOffice.Value .Value, DBNull.Value))

In C#, I know there's no implicit conversion for nullables, hence you can't use ??, but why is the first part of the IIf being evaluated in VB.NET?

Echilon
  • 10,064
  • 33
  • 131
  • 217

2 Answers2

9

The reson for this is that Iif is a function, so both the true value and false value are evaluated before the condition.

Instead, use If i.e.:

 cmd.Parameters.AddWithValue("@HOValue", If(headOffice.Value.HasValue, headOffice.Value.Value, DBNull.Value)) ' Assuming you've already checked that headOffice.Value IsNot Nothing
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
3

Iff is a function, i.e. its arguments are evaluated before it is executed. When headOffice.Value is null, then headOffice.Value.Value cannot be evaluated here.

Al Kepp
  • 5,831
  • 2
  • 28
  • 48
  • That makes sense and intensifies my VB hatred even more. Thanks for the info though. – Echilon Sep 14 '11 at 13:09
  • 2
    @Echilon there is also a 3-part `If` that does what you want without this pain. – Marc Gravell Sep 14 '11 at 13:12
  • 1
    The if statement in vb 2008 and higher can act like the ternary operator you seek. If(headOffice.Value.HasValue, headOffice.Value.Value, DBNull.Value) http://blogs.msdn.com/b/vbteam/archive/2008/03/11/if-operator-a-new-and-improved-iif-sophia-salim.aspx – CheckRaise Sep 14 '11 at 15:46