Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB CStr, CDate, CBool, etc. vs. DirectCast for casting without conversion

I usually avoid VB's built-in conversion functions (CStr, CDate, CBool, CInt, etc.) unless I need to do an actual conversion. If I'm just casting, say from an object to a string, I normally use either DirectCast or TryCast, under the assumption that CStr, etc., are doing some extra stuff I don't need. But sometimes the DirectCast syntax is a little cumbersome, as in the following example.

Dim value1 As String
Dim value2 As String
Using cn As New SqlConnection(cnStr)
    Using cmd as New SqlCommmand(sqlStr, cn)
        Using reader = cmd.ExecuteReader()
            While reader.Read()
                value1 = DirectCast(reader("COLUMN1"), String)
                value2 = CStr(reader("COLUMN1"))
            End While
        End Using
    End Using
End Using

SqlDataReader.Item returns an Object, which needs to be cast to a String. CStr is easier to read, type, and explain (IMO).

My question is, does it matter which one I use? Should I just go with CStr (and CDate and CBool, etc.) and not worry about the extra work I assume those functions are doing?

Is there any other downside to using these functions?

like image 960
John M Gant Avatar asked Dec 17 '22 06:12

John M Gant


1 Answers

This is a good post with discussion in the comments about DirectCast versus the CType casts and variations.

In short, if you want to be explicit about it and know what to expect, DirectCast is suggested. On the other hand, a comment by Paul Vick (VB Technical Lead) says it doesn't matter much and to just use the CType variations.

Some useful links gleaned from that post:

  • How should I cast in VB.NET?
  • DirectCast Revealed (post on Paul Vick's blog)
like image 56
Ahmad Mageed Avatar answered Dec 21 '22 22:12

Ahmad Mageed