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

I usually avoid the built-in VB conversion functions (CStr, CDate, CBool, CInt, etc.) unless I need to do the actual conversion. If I just cast, say, from an object to a string, I usually use DirectCast or TryCast, assuming CStr, etc. Do some extra things that I don't need. But sometimes DirectCast syntax is a bit 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 the object that must be passed to String. CStr is easier to read, enter, 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 that I assume that these functions are performed?

Is there any other drawback to using these features?

+4
source share
3 answers

This is a good post with a discussion in the comments about DirectCast compared to CType sheets and variations.

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

Some useful links gleaned from this post:

+10
source

In your example, you can simply use:

 value1 = reader("COLUMN1").ToString() 

It will return the contents of the column as a string.

I always prefer to use ToString () for an object, if possible. Sometimes the Object ToString () method returns objects such as the class name of the object, not the content, so .ToString () is not always an option.

I do not see the need for any VB functions CStr, CInt, etc., since the .NET environment provides many good alternatives. For instance.

 Dim value As Integer = Convert.ToInt32(reader("Number").ToString()) 

This is a good way to convert a string to int. It’s worth reading these conversion methods, because old VB style functions exist only for backward compatibility.

+1
source

In most cases, I use CStr, CInt, CBool, and CType because it is shorter and easier to read. There may be a small execution cost, but most of the time it does not matter. It is good to know the differences between CType, TryCast, DirectCast and others.

0
source

All Articles