Omitting DirectCast for BackgroundWorker e.argument
Most code I've seen uses DirectCast inside DoWork for e.argument.
Is it bad practice to omit it if the variable datatype is the same?
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim theArguments() As String = {Checkbox1.Checked, Textbox1.Text}
BackgroundWorker1.RunWorkerAsync(theArguments)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim theStrings() as String
theStrings = e.Argument
'vs
theStrings = DirectCast(e.Argument, String())
End Sub
Re: Omitting DirectCast for BackgroundWorker e.argument
It's bad practice because, in order to do so, you must have Option Strict set to Off, which you should pretty much never do. The e.Argument property is type Object because it has to be able to refer to any type of object. With Option Strict On, you can't assign an Object reference to any variable that isn't itself type Object. You have to perform the cast in order to tell the compiler that you are taking responsibility for making sure that the actual object at run-time will be that type.
So, you should turn Option Strict On in the project properties and then fix any errors that are flagged, which will all be related to use of the wrong types. You should also turn it On in the IDE options so that it will be On by default for all future projects. You will then be forced to always use the data type that is expected. That may seem like a pain but it will help you write better, faster and more robust code.
Re: Omitting DirectCast for BackgroundWorker e.argument
Another way to say that is that somebody will be doing the conversion. With DirectCast, you are doing it explicitly, but if you leave it out (and leave Option Strict OFF) then it will still happen, it's just that the compiler will do it implicitly. Essentially, an Object may or may not actually be an array of strings. You imply that it is, because you are assigning an Object to a variable of type array of string, so the compiler will take your word for it and attempt the cast. If it fails, then so does your program. In this case, it won't fail because the Object really IS an array of strings. However, that implicit conversion that the compiler does is often not quite as efficient as the explicit conversion that you do with DirectCast. The compiler is a bit more cautious about it.
So, while it will certainly work in this case, it won't be quite as efficient, and it will ONLY work if you have Option Strict OFF, which will let you do much worse things than this harmless conversion.