Implicit casting in VB.NET

The question is for lazy VB programmers. You are welcome.

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 know exactly the expected runtime type, is it "forbidden" to rely on inline casting in vb? When can I rely?

+2


source to share


4 answers


Comment for MarkJ for OP's answer



Feel free to rely on whatever you want, just make sure you know the rules for what the implicit cast does. However, example # 4 looks very easy to break through in the future, I would be much happier if there was even a zero check before.

+1


source


Of course, not "forbidden" to use Option Strict Off

, but almost everyone strongly advises using Option Strict On

.



The reasons are explained in other questions, for example.

+3


source


If you're using Visual Basic 2008, the other option explicates (for example, Option Strict On) and relies on Option Implicit On, so you don't have to write this type twice.

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

      

0


source


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 be automatically applied to the intended type under any circumstance and across all locales?

Pondering all the possible ramifications and handling almost inevitable errors will probably take more time than just strictly typing your variables, strictly checking your inputs, and explicitly throwing where needed.

0


source







All Articles