VB.NET Char Examples

The VB.NET programming language

The Char type is useful in the VB.NET programming language. 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.

This VB article shows the Char type. Chars are values. They represent characters.

Example

Note

To start, this example shows how you can 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.

Program that uses Char Dim [VB.NET]

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

Output

True

Chars in Strings

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. You would need a Char array or a StringBuilder for a mutable character buffer.

Char Array Use StringBuilder Examples
Program that uses Char in String [VB.NET]

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

Output

First character is D

Char to 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. In this program, these is no difference between the two.

Program that converts Char to Integer [VB.NET]

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

Output

97
98

Summary

The Char type is essential to most VB.NET programs 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. This means they will use less memory than a one-character String. Despite this, compatibility and correctness are most important in your VB.NET program.

VB.NET Tutorials
.NET