views:

71

answers:

4

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?

A: 

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)
ggf31416
I know all of that, I think you misunderstood my point.
Shimmy
+3  A: 

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.

MarkJ
Agree, its not forbidden, its just frowned upon. 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.
Chris Haas
@Chris, if you would place your post separately I'd mark it as answer.
Shimmy
Thanks @Shimmy, moved to an answer now
Chris Haas
+1  A: 

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.

Chris Haas
A: 

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.

John M Gant
I am not sure. I bet you're a C#er. The same risk I would take when explicitly casting a variable (why do I cast, because I know the expected type), I can rely on the lang built-in auto-cast feature, and that's why I am a VBer and I am so addicted to it.I just wanted to make sure it's not officially deprecated.
Shimmy