0

The following:

Delegate Function OperationDelegate(ByVal x As Double) As Double
Public Function test(Optional ByRef operation As OperationDelegate = AddressOf DefaultOperation) As Double
    Return operation.Invoke(3)
End Function

gives me the error: Constant Expression is required. Addressof DefaultOperation is causing the error using Visual Studio 2013.

I have tried defining DefaultOperation in the two following ways.

Public Function DefaultOperation(ByVal x As Double) As Double
    Return x
End Function

Dim DefaultOperation As OperationDelegate = Function(x As Double) As Double
                                                Return x
                                            End Function

In either case it has not worked. This is the ressource I have been using: https://msdn.microsoft.com/en-us/library/bb531253.aspx

Anyways thanks for your time.

A similar questions that I found:

Community
  • 1
  • 1
shammancer
  • 397
  • 2
  • 4
  • 8
  • 2
    As you can see from the similar questions you linked to. The default value for an optional argument must be a constant (its value must be known at compile time). It can't be a lambda. – Blackwood Jan 27 '16 at 19:02

1 Answers1

0

As suggested in the comments on your original post, a lambda can not be used as an optional parameter.

An alternative would be to overload the function (test, in your example) with a version with no parameters and a version with a delegate parameter.

Delegate Function OperationDelegate(ByVal x As Double) As Double

Public Function test() As Double
   Return test(AddressOf OperationDelegate)
End Function

Public Function test(operation As OperationDelegate) As Double
   Return operation.Invoke(3)
End Function
B Pete
  • 936
  • 1
  • 7
  • 16