Implicit casting in VB.NET

2019-07-16 05:01发布

问题:

The question is intended for lazy VB programmers. Please.

In vb I can do and I won't get any errors.

Example 1

Dim x As String = 5
Dim y As Integer = "5"
Dim b As Boolean = "True"

Example 2

Dim a As EnumType = 4
Dim v As Integer = EnumType.EnumValue

Example 3

Private Sub ButtonClick(sender As Object, e As EventArgs)
    Dim btn As Button = sender        
End Sub

Example 4

Private Sub ButtonClick(sender As Button, e As EventArgs)
    Dim data As Contact = sender.Tag
End Sub

If I surely know the expected runtime type, is this 'forbidden' to rely on the vb-language built-in casting? When can I rely?

回答1:

Comment to MarkJ move to answer per OP

Feel free to rely on it all you want, just make sure you know the rules for what the implicit cast is doing. That said, example #4 looks really easy to break in the future, I'd be much happier if there was at least a null-check before.



回答2:

It is certainly not "forbidden" to use Option Strict Off but nearly everyone strongly advises using Option Strict On.

The reasons are explained in other questions, for instance this.



回答3:

If you are using Visual Basic 2008, another option is doing the casting explicitaly (e.g. Option Strict On) and rely on the Option Implicit On so you don't need to write the type twice.

Dim x = 5.ToString()  
Dim data = DirectCast(sender.Tag, Contact)


回答4:

The irony of "lazy" practices like this is that they often end up costing you more time in the long run. Can you really be absolutely certain that your inputs will always be in a format that can automatically be cast to the intended type, under all circumstances and in all locales?

Thinking through all the possible implications, and handling the almost inevitable bugs, will probably take more time than just strongly typing your variables, strictly validating your inputs, and explicitly casting where needed.