- INDEX VB TO NET
- HOW TO MODIFY THE WAY THE CODE IS GENERATED
- LATE BINDING ACCESS THROUGH REFLECTION HELPER
Late Binding Access through ReflectionHelper
The VB6 typing model allows late binding. This means, variables may not have been declared with their actual type, but with a general type. E.g.: Control instead of Label, Form instead of Form1 or Variant instead of any other type.
Even when the variables are declared with a general type, the code can assume they contain an instance of a more specific type and access members from the latter. Neither the VB6 compiler nor the interpreter will raise an error if the actual type of the instance has the requested member.
On the other side, .NET will give a compilation error whenever a member is not in the declared type of the variable.
VBUC solves most of these issues by using its typing mechanism. This module is able to identify and resolve most late binding cases and correct the declarations with their actual type before performing the conversion process. This mechanism allows solving the member access as well as many other typing-related upgrade issues.
However, some variables take several values with inconsistent types and there is no way to infer a proper type for them.
The “Generate Reflection Helper” optional feature generates reflection calls for these latest cases which were not solved by the typing mechanism.
The reflection calls avoid the .NET compilation errors and provide an equivalent behavior in many cases. However it must be realized that not all the cases will behave in the same way since the upgrade process still lacks information about the actual type of the variable and its member during the application runtime. This is a simple example of the reflection helper usage:
Original VB6 Code:
Private Sub ShowInfo(useForm As Boolean) Dim x As Variant If useForm Then Set x = Form1 Else Set x = New Class1 End If If useForm Then MsgBox x.formProp Else MsgBox x.classProp End If End Sub
Resulting VB.NET Code:
Private Sub ShowInfo(ByRef useForm As Boolean) Dim x As Object If useForm Then x = Me Else x = New Class1 End If If useForm Then 'UPGRADE_TODO: (1067) Member formProp is not defined in type Variant. MessageBox.Show(ReflectionHelper.GetMember(x, "formProp"), Application.ProductName) Else 'UPGRADE_TODO: (1067) Member classProp is not defined in type Variant. MessageBox.Show(ReflectionHelper.GetMember(x, "classProp"), Application.ProductName) End If End Sub
Resulting C#.NET Code:
private void ShowInfo( bool useForm){ object x = null; if (useForm){ x = Form1.DefInstance; } else{ x = new Class1(); } if (useForm){ /UPGRADE_TODO: (1067) Member formProp is not defined in type Variant. MessageBox.Show(Convert.ToString(ReflectionHelper.GetMember(x, "formProp")), Application.ProductName); } else{ //UPGRADE_TODO: (1067) Member classProp is not defined in type Variant. MessageBox.Show(Convert.ToString(ReflectionHelper.GetMember(x, "classProp")), Application.ProductName); } }