
You want to convert a literal such as an Integer, Boolean, or Char into its String representation in your VB.NET program. In VB.NET, you cannot call the ToString function on these types. Instead you can use the built-in CStr function.
This VB article covers the CStr built-in Function. It converts values into Strings.
This simple program shows how you can convert the Integer 5 into the String "5" by calling the CStr function and passing 5 as the argument. Next, it shows that you can convert the Boolean True into the String "True" by using the CStr function as well. Finally, it converts the Char (a) into the String "a".
Program that uses CStr function [VB.NET]
Module Module1
Sub Main()
' Convert integer to string.
Dim str As String = CStr(5)
If str = "5" Then
Console.WriteLine(str)
End If
' Convert bool to string.
str = CStr(True)
If str = "True" Then
Console.WriteLine(str)
End If
' Convert char to string.
str = CStr("a"c)
If str = "a" Then
Console.WriteLine(str)
End If
End Sub
End Module
Output
5
True
a
How does the .NET Framework implement the CStr function in Visual Basic .NET? It is compiled CStr into the Conversions.ToString function. This eventually returns the correct String value for you to use. Note that the CStr("a"c) call above is optimized out by the Visual Basic .NET compiler for better performance.
The CStr function in the Visual Basic .NET language provides a way to effectively convert value types into String types. It is useful because you cannot call ToString on literals in the VB.NET environment. Finally, we noted how this method is implemented in the .NET Framework.
VB.NET Tutorials