Home

Search

VB.NET Char ExamplesUse the Char type. Chars are values that represent characters like letters and digits.
dot net perls

Char. The Char type is useful. Chars are value types. This means they are located in the bytes on the evaluation stack. You can get individual Chars from a String variable. One point of confusion occurs when converting Chars to Integers.

Integer

Example. To start, this example shows how to declare and assign a variable of type Char in a VB.NET program. In this program, the Char is initialized to the value "P" and then True is written to the screen.

VB.NET program that uses Char Dim
Module Module1 Sub Main() ' Char variable. Dim c As Char = "P" ' Test it. If c = "P" Then Console.WriteLine(True) End If End Sub End Module
True

String, Char. Next, we recall that Strings are composed of individual characters. With a special syntax, we can get these Chars. Please note that 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

StringBuilder

VB.NET program that uses Char in String
Module Module1 Sub Main() ' String variable. Dim s As String = "Dot Net Perls" ' 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 programming language, we must use a built-in conversion function. To get the ASCII number for a Char value, use Asc or AscW.

Here In this program, there is no difference between the two. Both of the built-in functions have the same effect.

VB.NET program that converts Char to Integer
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

Summary. The Char type is essential because of its usage in the String type. When possible, manipulating and handling Chars is preferable to Strings because they are values, not reference types. They use less memory than a one-character String.

Note Despite this, compatibility and correctness are most important in a VB.NET program.

Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.