VB.NET Char ArrayUse Char arrays with array initializers and the ToCharArray function.
dot net perls

Char array. A Char array stores characters together. In some VB.NET programs we need to use an array of characters instead of a String.

Array benefits. With Char arrays we employ certain spatial memory optimizations. This type is a useful construct. We can replace StringBuilder usage.



An example. This program declares and instantiates a char array in 3 ways. Usually in programs, the shortest syntax form is best, as it reduces the amount of text to read.

Version 1 First, the shortest syntax is used. The type of the array is only specified in the variable type.

Version 2 Second, the array is allocated upon the managed heap and then each element is assigned in a separate statement.

Version 3 Third, the New Char() syntax is used with an array initializer. This is also a short syntax form.

Note All of the arrays have identical contents when examined during execution.

VB.NET program that uses char arrays
Module Module1 Sub Main() ' Version 1: use the initializer syntax. Dim array1() As Char = {"a", "b", "c"} ' Version 2: use the long syntax. Dim array2(2) As Char array2(0) = "a" array2(1) = "b" array2(2) = "c" ' Version 3: another syntax. Dim array3() As Char = New Char() {"a", "c", "c"} ' Display lengths. Console.WriteLine(array1.Length) Console.WriteLine(array2.Length) Console.WriteLine(array3.Length) End Sub End Module
3 3 3

Example 2. With a char array, we can allocate the Char buffer all at once, and then assign into each element. We do not need to resize the buffer.

And The other approach you could use, which is slower, is the StringBuilder type and its Append function.

VB.NET program that assigns into char array
Module Module1 Sub Main() ' Allocate array of 100 characters. Dim array(100) As Char ' Fill array with a character. For index As Integer = 0 To 100 array(index) = "-" Next ' Write some characters. Console.WriteLine(array(0)) Console.WriteLine(array(100)) End Sub End Module
- -

ToCharArray. The easiest way to get a char array is probably ToCharArray. We can specify a string literal, and create an array from the characters with this function in just one line.


VB.NET program that uses ToCharArray
Module Module1 Sub Main() Dim value As String = "test" ' Get char array from string. Dim array() As Char = value.ToCharArray() ' Loop and print the chars. For Each element As Char In array Console.WriteLine("CHAR: {0}", element) Next End Sub End Module

Performance. How much faster is using a Char array to build up a sequence of characters in memory than is using a StringBuilder? This optimization can result in a 10X speedup.

A summary. A char array is the ideal array type for building up character data. It conforms to the standard array syntax in VB.NET. It can help many programs.

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