Array literals/constants as default arguments in functions?

  • Thread starter Urs van Binsbergen
  • Start date
U

Urs van Binsbergen

Hi!

This sounds probably quite silly, but I just can't figure out this one.
Consider the following which lets "a" be an array with 0 elements:

Dim a() As Integer
a = New Integer() {}

Now what do I have to code if I want an empty array as default value in
a function? This one doesn't work:

Function test(Optional ByVal a As Integer() = New Integer() {})
End Function

It says: Constant expression required. Is this not possible in general
because default values can only be simple types?

Greets and thanks,
Urs
 
A

Armin Zingler

Urs van Binsbergen said:
This sounds probably quite silly, but I just can't figure out this
one. Consider the following which lets "a" be an array with 0
elements:

Dim a() As Integer
a = New Integer() {}

Now what do I have to code if I want an empty array as default value
in a function? This one doesn't work:

Function test(Optional ByVal a As Integer() = New Integer() {})
End Function

It says: Constant expression required. Is this not possible in
general because default values can only be simple types?

Yes. Add an overloaded version:

Function test()
Test(New Integer() {})
End Function
 
J

Jay B. Harlow [MVP - Outlook]

Urs,
In addition to the overload that Armin used.

Seeing as the parameter is an Optional array, consider using a ParamArray
instead:

Function Test(ByVal ParamArray a() As Integer) As Integer
End Function

Then when you call it, passing no parameters you will get an empty array.

Dim x As Integer
x = Test()

Passing a list of intergers you will get an array of integers.

x = Test(1,2,3,4,5)

Passing an array of integers you will get that array of integers.

Dim a() As Integer = {1,2,3,4,5}
x = Test(a)

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top