Previous | Index | Next 

[HOWTO] Reduce runtime errors caused by null strings

In VB6 an uninitialized string variable contains an empty string, that is “” or a zero-char string. In VB.NET, an uninitialized string variable contains a null string, or Nothing. Likewise, a VB6 string array contains all empty strings, whereas all the elements of a VB.NET string array are equal to Nothing.

VB Migration Partner mitigates this problem by explicitly initializing all string variables to an empty string. In other words, the following VB6 code:

        Dim s As String

is translated to .NET as:

        ' VB.NET
        Dim s As String = ""
        // C#
        string s = "";

However, a string equal to Nothing may come up when evaluating an expression or when extracting items from an array. Once you spot the problem, you just need to insert one or more statements that convert null strings to empty strings. Better yet, the VBMigrationPartner_Support module contains a couple of functions – FixNullString6 and FixNullStringArray6 - that perform this action for you. For example, suppose that you have the following VB6 code:

        Dim s As String
        Dim arr() As String
        ' ...
        s = SomeMethod(1)
        arr = SomeArrayMethod(2, 5)

If you suspect that SomeMethod and SomeArrayMethod may return null strings, you just need to add the VBMigrationPartner_Support module to the current project and transform the code as follows:

        s = FixNullString6(SomeMethod(1))
        arr = FixNullStringArray6(SomeArrayMethod(2, 5))

Alternatively, you can use these special methods as procedures instead of functions. In this case, you don’t need to add the VBMigrationPartner_Support module to the project and achieve the same effect with an InsertStatement pragma:

        s = SomeMethod(1)
        '## InsertStatement FixNullString6(s)
        arr = SomeArrayMethod(2, 5)
        '## InsertStatement FixNullStringArray6(arr)

When converting to C#, the two pragmas are slightly different:

        s = SomeMethod(1)
        '## InsertStatement VB6Helpers.FixNullString(ref s);
        arr = SomeArrayMethod(2, 5)
        '## InsertStatement VB6Helpers.FixNullStringArray(arr);

 

Previous | Index | Next