Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET Nullables

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?

like image 885
Echilon Avatar asked Feb 12 '26 08:02

Echilon


2 Answers

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
like image 123
Rowland Shaw Avatar answered Feb 15 '26 05:02

Rowland Shaw


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.

like image 44
Al Kepp Avatar answered Feb 15 '26 05:02

Al Kepp