'Pass and store optional delegate in variable

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source