HomeSearch

VB.NET CStr Function

This VB.NET article covers the CStr built-in Function. It converts values into Strings.
CStr converts literals into Strings. It handles Integer, Boolean and Char. It changes these into their String representations. In VB.NET we cannot call the ToString function on these types. Instead we use the built-in CStr function.IntegerChar
Example. This simple program shows how to convert the Integer 5 into the String "5". It calls the CStr function and passes 5 as the argument. It shows that you can convert the Boolean True into the String "True" by using the CStr function.

Finally: It converts the Char (a) into the String "a". It uses the CStr function for this as well.

Strings
VB.NET program that uses CStr function 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
Internals. 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.

Note: The CStr("a"c) call above is optimized out by the Visual Basic .NET compiler for better performance.

Summary. The CStr function in the Visual Basic .NET language provides a way to effectively convert value types into String types. It is useful—you cannot call ToString on literals in the VB.NET environment.

Also: We noted how the CStr function is implemented in the .NET Framework internals.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls