Home > Back-end >  Pass and store optional delegate in variable
Pass and store optional delegate in variable

Time:02-10

I'm trying to pass an optional callback parameter to my class when I instantiate it. I need a callback method to format some value that may or may not need formatting.

Here is my simplified code of what I am trying to do:

Public Class ColumnSpec
    Property Title As String
    Property Name As String
    Property Value As String

    Delegate Function CallBack(aValue As String) As String
    Property HasCallBack As Boolean

    Public Sub New(aTitle As String, aName As String, Optional aCallBack As CallBack = Nothing)
        _Title = aTitle
        _Name = aName
        ' How do I assign aCallBack to the delegate function here?
        _HasCallBack = aCallBack IsNot Nothing
    End Sub
End Class

I may or may not pass a callback function when instantiating ColumnSpec.

In another class, I need to check and call the delegate.

Public Class MyClass

   Public Function FormatText(Value as String) As String
       Return Value   "01234"  ' Return value after modifying
   End Function

   Public Function RenderValue() As String
       Dim lNewCol1 as ColumnSpec("Title1", "Name2", AddressOf FormatText)
       Dim lNewCol2 as ColumnSpec("Title2", "Name2")

       ' How do I check if there is a delegate and call it?
       If lNewCol1.HasCallBack Then lNewCol1.Value =  lNewCol1.CallBack(lNewCol1.HasCallBack)
       If lNewCol2.HasCallBack Then lNewCol2.Value =  lNewCol1.CallBack(lNewCol2.HasCallBack)
   End Function
End Class

I am completely new to delegates. Any ideas on how I can solve this?

CodePudding user response:

Your line Delegate Function CallBack(aValue As String) As String only declares the type of the callback. You need a separate property or field to hold the reference.

So, you would modify the class slightly:

Delegate Function CallbackFunction(aValue As String) As String

Public ReadOnly Property Callback As CallbackFunction

Public ReadOnly Property HasCallback As Boolean
    Get
        'Alternatively, you could assign the value in the ctor as in your code...
        Return Callback IsNot Nothing
    End Get
End Property

Public Sub New(Optional aCallback As CallbackFunction = Nothing)
    Me.Callback = aCallback
End Sub

Your client code is fine as-is and doesn't need to be changed.

If you don't care about having a named type for the callback function, you could also use newer syntax, e.g.

Public ReadOnly Property Callback As Func(Of String, String)

Also modifying the constructor accordingly.

The client code would still work fine as-is with this modification.

(Action is to Sub as Func is to Function.)

  • Related