Specifying default array values in an optional array parameter

arrays, optional-parameters, vb.net

Solution

It is not a "constant expression", an expression that can be entirely evaluated at compile time and produces a single simple value that can be stored in the assembly metadata. To be used, later, in other code that makes the call. Optional values are retrieved at compile time, not runtime, strictly a compiler feature.

The New operator must be executed at runtime and requires code to do so. And is therefore not a constant expression. The simple workaround is to use Nothing and put the code in the method body:

Sub Foo(Optional ByVal myArray As Long() = Nothing)
    If myArray Is Nothing Then myArray = New Long() {0, 1}
    '' etc...
End Sub

Problem

Optional parameters require default values, yet I can't seem to assign a default array to an optional array parameter. For example: ``` Optional ByVal myArray As Long() = Nothing ' This works ``` However ``` Optional ByVal myArray As Long() = New Long() {0, 1} ' This isn't accepted. ``` The IDE tells me that a "constant expression is required" in place of `New Long() {0, 1}`. Is there a trick to assigning a default array of constants, or is it not allowed?

Original source