What is the difference between these blocks of code, why the first one does not work, and how do I debug this?

I wrote:

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

and all this is fine, but when placeholderMRTK is really nothing, it fails without throwing an exception, just leaving the sub (MyBase.Load for the dialog form) and continuing to work with the application. When I rewrite it as:

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

It works great. I thought these two are logical equivalents.

So:

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

2) Why can the first fail? I wonder if this is some kind of creepy type conversion problem, but are both placeholderMRTK and MfgRecipeTypeKey declared as Byte? (with zero byte).

3) Why execution just drops out of sub without representing me with an exception. When this line is highlighted in Visual Studio (if it matters for Pro 2013), and f11 for the next line, it just jumps and fires the datagrid rendering event, and then presents my dialog, but without any important data assignments occurring under hood, And given that he is doing this (is this new behavior in 2013?), How should I debug?

Thank you for your time and attention!

+5
source share
2 answers

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

This is 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 to implicitly convert 0 to Byte .


you can use

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

convert 0 to Byte or just use

 MfgRecipeTypeKey = If(placeholderMRTK, 0) 
+4
source

You can use the built-in GetValueOrDefault function.

 MfgRecipeTypeKey = placeholderMRTK.GetValueOrDefault(0) 
+1
source

All Articles