CStr() Str() .ToString()

ToString will call the .ToString() function on a particular instance. In practice, this means that it will throw an exception if the object in question is Nothing. However, you can implement .ToString() in your own classes to get a useful string representation of your object, whereas CType/CStr only work with built-in classes and interfaces.

CStr and CType(expression, String) are exactly equivalent (I'm not sure where the other poster got the idea that CStr is faster). But they aren't really functions, they're compiler directives that will emit very different code depending on the declaration of expression. In most cases, these directives call a bunch of internal VB code that tries to get a reasonable string out of expression.

DirectCast(expression, String) assumes that the expression in question really is a String and just casts it. It's the fastest of all these options, but will throw an exception if expression is anything other than a String.


I don't know about ToString() and i don't know about VB.NET

But in VB6 (Visual Basic 6):

Both of Cstr() and Str() converts values to string. but Cstr() is better because:

Str(): After converting to string it adds 1 space before positive numbers. for example: Str(22) > " 22"

Cstr(): After converting to string it never adds the above extra space - For best result use it with Trim() - Trim(Cstr(Variable))


As an Addition to the VBA/VB6 Environment where we have no ToString():

  • Str() is not aware of international representation. The decimal separator always is a dot (.).

    As already mentioned above it prefixes the resulting string with a blank in case of positive values.

  • There also exists Str$(). The difference to Str() is the return type:

    Str() returns a variant of type string, Str$() returns a string.

    And Str$() is slightly faster then Str().

  • CStr() in contrast is aware of international representation. The decimal separator depends on the Windows international settings.

    No additional prefixing for positive values will be done.

So if you need to convert a value type to a string and have to ensure a dot as a decimal separator and no prefixing blank, then use this syntax:

Dim d As Double
d = 123.456

Dim s As String
s = Trim(Str$(d))

Tags:

Vb.Net

String