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 conversi开发者_JAVA技巧on 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 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
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.
加载中,请稍侯......
精彩评论