Question "Option Explicit On" issue with implicit conversion

keith_co

New member
Joined
Sep 25, 2012
Messages
2
Programming Experience
1-3
With Option Explicit On I get a implicit coversion error with the code listed below.
If I turn off option explicit I get a warning, but it compiles and runs fine.
I can not figure out how to rewrite this to get the conversion right.
I use this code to pass some text up to the main form from a background worker.
Thoughts?

Thanks,

Keith

9-26-2012 11-30-35 AM.jpg
'used to set form objects with data from background workers
Public Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.TextBox1.InvokeRequired Then
Dim d As New ContextCallback(AddressOf SetText)
Me.Invoke(d, NewObject() {[text]})
Else
Me.TextBox1.Text = [text]
End If
End Sub
 
Public Sub SetText(ByVal [text] As String) should be Public Sub SetText(ByVal [text] As Object)
You then cast the object to a string when assigning it to the Text property:
Else
Me.TextBox1.Text = [text].ToString
End If
 
Or don't use a ContextCallback delegate. You can use any delegate when you call Invoke so, if you want to call a method with one String parameter and no return type, use a delegate with one String parameter and no return type. You can define such a delegate yourself or just use the Action(Of String) delegate.

Also, since .NET 2.0 (I think) the second parameter of the Invoke method has been a ParamArray, meaning that you can simply pass zero, one or more individual objects rather than having to explicitly create an array. That means that your code would best look like this:
Public Sub SetText(ByVal text As String)
    If TextBox1.InvokeRequired Then
        TextBox1.Invoke(New Action(Of String)(AddressOf SetText), text)
    Else
        TextBox1.Text = text
    End If
End Sub
By the way, you're talking about Option Strict, not Option Explicit. Explicit relates to whether or not variables must be explicitly declared before use. Strict relates to strict typing, i.e. whether or not late-binding and implicit conversions are allowed.
 
Back
Top