CStr Function
This page was last reviewed on Dec 22, 2023.
Dot Net Perls
CStr. This converts literals into Strings—it handles Integer, Boolean and Char. It changes these into their String representations. In VB.NET we can use the built-in CStr function.
ToString note. In VB.NET, we can call ToString, which is more like how things work in the C# language. Often, using ToString is preferred as it is more standard.
Example. This program 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.
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
5 True a
Internals. How does the .NET Framework implement the CStr function? 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 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (edit).
© 2007-2024 Sam Allen.