简体   繁体   中英

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?

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 ie:

 cmd.Parameters.AddWithValue("@HOValue", If(headOffice.Value.HasValue, headOffice.Value.Value, DBNull.Value)) ' Assuming you've already checked that headOffice.Value IsNot Nothing

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM