0

I was working on a function that accepts ParamArrays. But it should have at least one element and the maximum of 5 elements. I tried defining array bounds but got an error Array bounds cannot appear in type specifiers.

So how can I do this?

hmak.me
  • 3,770
  • 1
  • 20
  • 33
  • 1
    This cannot be enforced at compile-time, you'll have to check at runtime and throw an exception when you're not happy. – Hans Passant Mar 23 '15 at 10:36

2 Answers2

1

So how can I do this?

You can’t. Not statically at least. The only thing you can do is check inside the function and throw an exception (e.g. an ArgumentException) when the wrong number of arguments is encountered.

In terms of API design this strikes me as weird, however. I don’t think a ParamArray is the best solution in your case, precisely because you seem to have restrictions which are not well reflected by a ParamArray.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Is there a way to throw exceptions when editing the code? like when we miss a non optional argument. – hmak.me Mar 23 '15 at 10:43
  • @HosseinMaktoobian Unfortunately I do not understand that question. – Konrad Rudolph Mar 23 '15 at 10:44
  • when you are using a function, if you miss an argument, it will underlines the function and the error is about number of arguments and it prevents compiling. How can I do this? – hmak.me Mar 23 '15 at 10:46
  • @HosseinMaktoobian You can’t. This is what “you can’t do this statically” means. The most you could do would be to write a rule plugin for a static analysis tool and annotate the function arguments with a custom attribute. However, this is a lot (and I mean *a lot*) of effort for next to no benefit. I strongly suggest solving this differently. As I’ve said, a `ParamArray` is probably not the correct solution here. – Konrad Rudolph Mar 23 '15 at 10:49
0

Not knowing the context of your question, I would suggest doing what you can to make the function signature honor the contract you are requiring. For instance:

Public Sub Grover (cheese1 as Cheese, Optional cheese2 as Cheese = Nothing, Optional cheese3 as Cheese = Nothing, Optional cheese4 as Cheese = Nothing, Optional cheese5 as Cheese = Nothing)
    If cheese1 Is Nothing Then
        'throw
    End If

    For Each cheese in {cheese1, cheese2, cheese3, cheese4, cheese5}
        If cheese IsNot Nothing Then
            cheese.Snozzle()
        End If

        'or, in VB14 (as of Visual Studio 2015)
        cheese?.Snozzle()
    Next
End Sub
Craig Johnson
  • 744
  • 4
  • 8