VB.NET Char ExamplesUse the Char type. Chars are values that represent characters like letters and digits.
Char. In VB.NET programs the Char type is useful. Chars are value types—this means they are located in the bytes on the evaluation stack.
Char notes. You can get individual Chars from a String variable. One point of confusion occurs when converting Chars to Integers.
String example. Strings are composed of individual characters. With a special syntax, we can get these Chars. You cannot assign Chars at indexes inside a string.
Tip To do that, you would need a Char array or a StringBuilder for a mutable character buffer.
Char Array
Module Module1 Sub Main() ' String variable. Dim s As String = "Delete" ' Char variable. Dim c As Char = "D"c ' Test first character of String. If c = s(0) Then Console.WriteLine("First character is {0}", c) End If End Sub End Module
First character is D
Char, Integer. In many programming languages, you can cast a Char to an Integer. In the VB.NET language, we must use a built-in conversion function.
Tip To get the ASCII number for a Char value, use Asc or AscW. In this program, there is no difference between the two.
Module Module1 Sub Main() Dim a As Char = "a" Dim b As Char = "b" Dim i As Integer = Asc(a) Dim i2 As Integer = AscW(b) Console.WriteLine(i) Console.WriteLine(i2) End Sub End Module
97 98
Byte size. In VB.NET and C#, Chars are 2 bytes. This means they can accommodate values outside of the ASCII range. But it may also cause more memory usage.
Summary. The Char type is used with the String type. When possible, manipulating and handling Chars is preferable to Strings because they are values, not reference types.
Final notes. Chars use less memory than a one-character String. Despite this, compatibility and correctness are most important in a VB.NET program.
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 3/22/2022 (image).
© 2007-2022 sam allen.
see site info on the changelog.