Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between these code blocks, why does the former fail, and how should I debug this?

Tags:

vb.net

I wrote:

    MfgRecipeTypeKey = If(placeholderMRTK Is Nothing, 0, placeholderMRTK)

and that's all fine, but when placeholderMRTK actually is Nothing, it fails, without raising an exception, just quitting the sub (MyBase.Load for a dialog form) and continuing on with the application. When I rewrite it as:

    If placeholderMRTK Is Nothing Then
        MfgRecipeTypeKey = 0
    Else
        MfgRecipeTypeKey = placeholderMRTK
    End If

it works fine. I thought the two were logical equivalents.

So:

1) What is the actual difference between those two that I don't know about?

2) Why might the first one fail? I sort of wonder if it's some screwy typecasting issue, but both placeholderMRTK and MfgRecipeTypeKey are declared as Byte? (nullable byte) types.

3) Why does execution just fall out of the sub without presenting me with an exception. When that line is highlighted in Visual Studio (Pro 2013 if it matters) and I f11 for next line, it just hops out and runs a datagrid rendering event and then presents my dialog, but without some important data assignments having taken place under the hood. And given that it does this (is this new behavior in 2013?), how am I supposed to be debugging?

Thanks for your time and attention!

like image 570
clweeks Avatar asked Jun 18 '15 15:06

clweeks


2 Answers

The If() operator with three arguments you use expects that the two possible branches return a value of the same type.

It's not the case when you use

MfgRecipeTypeKey = If(placeholderMRTK Is Nothing, 0, placeholderMRTK)

since placeholderMRTK is of type Nullable(Of Byte) and 0 is of type Integer.


 If placeholderMRTK Is Nothing Then
     MfgRecipeTypeKey = 0
 Else
     MfgRecipeTypeKey = placeholderMRTK
 End If

works because VB.Net allows you the implicit conversion of 0 to Byte.


You could use

MfgRecipeTypeKey = If(placeholderMRTK Is Nothing, CType(0, Byte), placeholderMRTK)

converting the 0 into a Byte, or simply use

MfgRecipeTypeKey = If(placeholderMRTK, 0)
like image 79
sloth Avatar answered Oct 20 '22 00:10

sloth


You could use the built-in function GetValueOrDefault.

MfgRecipeTypeKey = placeholderMRTK.GetValueOrDefault(0)
like image 23
the_lotus Avatar answered Oct 20 '22 00:10

the_lotus