VB.NET Val and Asc Function Examples

The VB.NET programming language

You have a Char in your VB.NET program and want to get either its integer representation or its numeric representation. Using the Val, Asc and AscW functions, we can convert characters into the appropriate integer value.

This VB program uses the Val, Asc and AscW built-in Functions.

Example

First, this program demonstrates these functions with two different characters. The character "a" has a Val of 0 and an Asc of 97. In ASCII, the letter 'a' is represented with the number 97. The Val function returned zero because "a" is not a number itself.

Program that uses Val, Asc, AscW [VB.NET]

Module Module1
    Sub Main()
	' Use Val and AscW on char.
	Dim c As Char = "a"c
	Dim i As Integer = Val(c)
	Dim a As Integer = Asc(c)

	Console.WriteLine(c)
	Console.WriteLine(i)
	Console.WriteLine(a)

	' Another character.
	Dim c2 As Char = "2"c
	Dim i2 As Integer = Val(c2)
	Dim a2 As Integer = AscW(c2) ' AscW is similar to Asc

	Console.WriteLine(c2)
	Console.WriteLine(i2)
	Console.WriteLine(a2)
    End Sub
End Module

Output

a
0
97
2
2
50
Char type

Second character. The second Char in this example contains the digit "2". The Val function here returns 2; this is the digit contained in the character. The AscW function here returns 50; this is the ASCII numeric representation for the character "2".

Summary

In this example, we saw how the Val, Asc, and AscW functions are useful in different situations. If you want to convert a Char to its underlying integer representation, the Asc and AscW functions are ideal. If you want to get the number from the Char and turn it into an Integer, the Val function is best.

VB.NET Tutorials
.NET