Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate function doesn't return value

I might be missing something obvious, but I'm not able to return a value with a delegate.

Private Delegate Sub ChangeTextDelegate(tb As TextBox)
Private Sub ChangeText(tb As TextBox)
    If tb.InvokeRequired Then
        tb.Invoke(New ChangeTextDelegate(AddressOf ChangeText), tb)
    Else
        tb.Text = "NEW TEXT"
    End If
End Function

Sub Delegate works well.

Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
    Else
        Return tb.TextLength
    End If
End Function

But this Function Delegate doesn't seem to work since i == 0 after dim i = TextLength(myTextBox), even though tb.TextLength == 68

Any idea ?

like image 635
Arthur Rey Avatar asked Apr 15 '26 14:04

Arthur Rey


2 Answers

You are not returning the value if the Invoke is required.

Try this instead:

Private Delegate Function TextLengthDelegate(tb As TextBox) As Integer
Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        Return CInt(tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb))
    Else
        Return tb.TextLength
    End If
End Function

However, you might find this code easier as you don't have to define a separate delegate:

Private Function TextLength(tb As TextBox) As Integer
    If tb.InvokeRequired Then
        Return CType(tb.Invoke(New Action(Of TextBox)(AddressOf TextLength), tb), Integer)
    Else
        Return tb.TextLength
    End If
End Function
like image 88
Matt Wilko Avatar answered Apr 17 '26 13:04

Matt Wilko


Doesn’t VS warn you about your code since it doesn’t return a value when invoking the delegate?

tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)

You have to return the value returned by Invoke, and since Invoke returns an Object, you need to cast the value:

Dim result = tb.Invoke(New TextLengthDelegate(AddressOf TextLength), tb)
Return DirectCast(result, Integer)
like image 23
Konrad Rudolph Avatar answered Apr 17 '26 14:04

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!