Previous | Index | Next 

[PRB] Passing an enumerated value to a Boolean argument throws an exception when the method returns

Consider the following VB6 code:

    Sub Form_Load()
        ' chkShow is a CheckBox control
        TestMethod chkShow.Value
    End Sub

    Sub TestMethod(state As Boolean)
        ' do something here
    End Sub

VB Migration Partner convents this code to VB.NET verbatim, not counting minor syntax differences. The problem is: when the call from TestMethod returns, the application throws an unexpected “Illegal property value” exception. It is important to understand why this happens and how you can avoid the runtime exception.

The CheckBox control’s Value property is an enumerated value that can take the value 0, 1, or 2. When such a value is passed to a Boolean argument, zero values are converted to False, whereas nonzero values are converted to True. In the latter case, on returning from the method, VB.NET attempts to assign True (or -1) to the Value property, which causes the exception because the CheckBox.Value property can't be assigned a negative value. The behavior occurs because the argument is passed by-reference and can’t be considered as a bug of VB.NET or VB Migration Partner. The easiest way to fix this problem is to use by-value semantics for the parameter. If the parameter is never assigned inside the method, VB Migration Partner correctly emits a warning about the unnecessary ByRef keyword:

' UPGRADE_INFO (#02C1): The 'state' parameter is neither assigned in current method nor 
' is passed to methods that modify it. Consider changing its declaration using the 
' ByVal keyword.

If you see the above remark in the migrated VB.NET you can confidently add a ByVal keyword in the original VB6 application without any fear to change the code’s behavior. Alternatively, you can use the UseByVal pragma to have VB Migration Partner do the fix for you.

 

Previous | Index | Next