Migrating Visual Basic 6.0 Optional Parameters to .NET

7. November 2008 05:53 by Jaguilar in General  //  Tags: ,   //   Comments (0)

In Visual Basic 6.0 you can specify optional parameters in a function or sub signature. This, however, isn't possible in .NET. In order to migrate code that uses this optional parameters, the Visual Basic Upgrade Companion creates different overload methods with all the possible combinations present in the method's signature. The following example will further explain this.

Take this declaration in VB6:

Public Function OptionSub(Optional ByVal param1 As String, Optional ByVal param2 As Integer, Optional ByVal param3 As String) As String
    OptionSub = param1 + param2 + param3
End Function

In the declaration, you see that you can call the function with 0, 1, 2 or 3 parameters. When running the code through the VBUC, you will get four different methods, with the different overload combinations, as shown below:

static public string OptionSub( string param1, int param2, string param3)

     return (Double.Parse(param1) + param2 + Double.Parse(param3)).ToString();
}

static public string OptionSub( string param1, int param2)

      return OptionSub(param1, param2, "");
}

static public string OptionSub( string param1)

      return OptionSub(param1, 0, "");
}

static public string OptionSub()

      return OptionSub("", 0, "");
}

The C# code above doesn't have any change applied to it after it comes out of the VBUC. There may be other ways around this problem, such as using parameter arrays in C#, but that would be more complex in scenarios like when mixing different data types (as seen above).

Categories