Delegates and ParamArray - Workarounds?

Some predefined methods contain ParamArray in their signature. However, delegates cannot contain ParamArray in their signature.

Question. Suppose you want to create a delegation mechanism for a specific method that requires a ParamArray. How would you get around this limitation?

EDIT: just to understand, suppose you yourself cannot change the method signatures themselves (predefined methods defined by some third party, whether Microsoft or not).

EDIT2: The real deal is to conserve syntactic sugar , since the following code really works, but eliminates sugar:

Public Delegate Sub MyDelegate(ByVal myArgs() As Object) Public Sub PredefinedSub(ByVal ParamArray myArgs() As Object) '...' End Sub Sub Test() Dim aDelegate As New MyDelegate(AddressOf PredefinedSub) aDelegate.Invoke(New Object() {1, 2, 3, 4}) End Sub 

EDIT3: It turns out that Skeet solutions are also applicable for creating events and statements containing ParamArray.

+6
method-signature delegates
source share
2 answers

Hmm ... it works in C #:

 using System; class Test { delegate void Foo(params string[] args); static void Main() { Foo f = x => Console.WriteLine(x.Length); f("a", "b", "c"); } } 

However, you are correct: this equivalent delegate declaration in VB is not executed:

 Delegate Sub Foo(ParamArray ByVal args() As String) 

gives:

error BC33009: "delegate" parameters cannot be declared as "ParamArray".

Curious. Fortunately, there is a way around this:

 Imports System Public Class Test Delegate Sub Foo(<[ParamArray]()> ByVal args() As String) Public Shared Sub Main() Dim f As Foo = AddressOf PrintLength f("a", "b", "c") End Sub Private Shared Sub PrintLength(ByVal x() As String) Console.WriteLine(x.Length) End Sub End Class 

Basically I just applied ParamArrayAttribute manually. This seems to be normal.

However, none of this would stop you from using existing ParamArray methods. These methods are quite capable of accepting normal arrays, so you could declare your delegate types as regular and still instantiated delegates that referenced these methods without any problems. The type of delegate only affects how you could call a delegate.

Other than declaring a delegate type with an array of parameters, I really don't understand what the problem is.

+17
source share

Are you sure delegates do not support ParamArray? Well, even if they don't, ParamArray is syntactic sugar for a plain old array. define the parameter as an array that it is.

0
source share

All Articles