Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying default array values in an optional array parameter

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?

like image 439
ingredient_15939 Avatar asked Mar 24 '14 13:03

ingredient_15939


Video Answer


1 Answers

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
like image 146
Hans Passant Avatar answered Nov 14 '22 23:11

Hans Passant