In Visual Basic (both Classic and .NET), optional parameters can be declared for procedures and functions using the Optional keyword. It is also possible to set default values for such parameters.
Syntax:
Sub SendMessage(message As String, Optional urgent As Boolean = False) If urgent Then Console.WriteLine("URGENT: " & message) Else Console.WriteLine(message) End If End Sub ' Calls: SendMessage("Hello!") ' urgent = False SendMessage("Important message!", True)
Important nuances:
Optionalparameters must always be the last in the parameter list.- If there is no default value for a parameter, it is defined as
Nothingor the default for its type (e.g., 0 for Integer).- In Classic VB, the types of Optional parameters are limited: types without default values (e.g., non-nullable classes) cannot be used.
Question: Can you declare a required parameter after an optional (Optional) one in Visual Basic? Explain why (no/yes) and how to avoid this.
Answer: No, after declaring at least one parameter as Optional, all subsequent parameters must also be declared as Optional. This is a syntactical requirement to avoid confusion when passing parameters by position.
Example of incorrect code:
Sub PrintReport(Optional pageSize As String = "A4", copies As Integer) ' Compilation error: required parameters cannot come after optional ones End Sub
To solve this — change the order of parameters:
Sub PrintReport(copies As Integer, Optional pageSize As String = "A4") ' Correct version End Sub
Story
On a large project, the client added an optional parameter to the file sharing procedure, forgetting about its required default value. Consequently, when calling the method without specifying the parameter,
Nothingwas processed as the filename, which caused a loading error.
Story
As a result of copying the method signature from another system, the order of parameters was broken — a required parameter went after
Optional. The programmer fixed the compilation error by only changing the order, but in all calls did not take into account that now the numbering had shifted. This caused the function to behave incorrectly in more than 30 places in the code.
Story
To shorten the code, it was decided to assign an empty string as the default value for a string parameter. However, in some cases, handling an empty value differed from handling a missing parameter and led to illogical dialog logic — instead of showing the standard text, it caused the form to hide without explanations.