Previous | Index | Next 

[HOWTO] Assign a specific data type when the As clause is missing

VB Migration Partner supports the InferType pragma, which attempts to infer a specific data type by analyzing the context in which a local variable, class field, property, function, or parameter is used. This pragma greatly reduces the number of code elements that are converted using the “As Object” clause to VB.NET

However, in many cases a VB6 code element hasn’t a specific type only because it is defined using this syntax:

        Dim x1, x2, y1, y2 As Integer

In fact, a common misconception among VB6 developers is that the above statement declares four Integer variables. The reality is, this statement declares only y2 as an integer variable, whereas the type of x1, x2, and y1 variables is affected by Defxxx statements (e.g. DefInt or DefDbl). If the current file contains no Defxxx statement, then the type of these variable is assumed to be Variant. When converted to VB.NET, they will become Object variables.

If you are migrating a VB6 application written by developers who consistently applied this sloppy coding practice, you can help VB Migration Partner to restore the intended data type by means of one or more PreProcess pragmas. More precisely, you need one pragma to account for Dim statements with two variables, another pragma to account for Dim statements with three variables, and so forth:

   '## PreProcess "\b(?<kw>Private|Public|Dim|Static)\b\s+(?<v1>\w+)\s*,
          "${kw} ${v1} As ${type}, ${v2} As ${type}", true

   '## PreProcess "\b(?<kw>Private|Public|Dim|Static)\b\s+(?<v1>\w+)\s*,
          "${kw} ${v1} As ${type}, ${v2} As ${type}, ${v3} As ${type}", true

   '## PreProcess "\b(?<kw>Private|Public|Dim|Static)\b\s+(?<v1>\w+)\s*,
          "${kw} ${v1} As ${type}, ${v2} As ${type}, ${v3} As ${type}, ${v4} As ${type}", true

   '## PreProcess "\b(?<kw>Private|Public|Dim|Static)\b\s+(?<v1>\w+)\s*,
          "${kw} ${v1} As ${type}, ${v2} As ${type}, ${v3} As ${type}, 
          ${v4} As ${type}, ${v5} As ${type}", true

When these pragmas are used, the above Dim statement is expanded into the following VB6 code immediately before the migration begins:

        Dim x1 As Integer, x2 As Integer, y1 As Integer, y2 As Integer

which, of course, is translated to VB.NET as:

        Dim x1 As Short, x2 As Short, y1 As Short, y2 As Short

Notice that these pragmas account for variables and class fields declared with Dim, Static, Public, and Private keywords. You can easily create similar PreProcess to account for more than five variables in a single line.


Previous | Index | Next