VB.NET Char Array

Use Char arrays with array initializers and the ToCharArray function.

Char array. A Char array stores characters together. In some programs we need to use an array of characters instead of a String. With Char arrays we employ certain spatial memory optimizations. This type is a useful construct.ArrayChar

Example. This program declares and instantiates a char array in three ways. First, the shortest syntax is used. Second, the array is allocated upon the managed heap and then each element is assigned in a separate statement.
And: 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() ' Use the quick syntax. Dim array1() As Char = {"s", "a", "m"} ' Use the long syntax. Dim array2(2) As Char array2(0) = "s" array2(1) = "a" array2(2) = "m" ' Another syntax. Dim array3() As Char = New Char() {"s", "a", "m"} ' Display lengths. Console.WriteLine(array1.Length) Console.WriteLine(array2.Length) Console.WriteLine(array3.Length) End Sub End Module Output 3 3 3

Example 2. A good use for a Char array is to achieve spatial memory optimization. You can allocate the Char buffer all at once, and then assign into each element as you go along. The enclosing buffer need not be resized, thus reducing memory usage.
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 Output - -

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.ToCharArray
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 Output CHAR: t CHAR: e CHAR: s CHAR: t

How much faster is using a Char array to build up a sequence of characters in memory than is using a StringBuilder? Sometimes, this optimization results in a speedup of ten times.

Summary. Representing the ideal array type for algorithms that must iteratively build up character data, the char array can be used for efficiency purposes. Because it conforms to the standard array syntax in VB.NET, the char array is easy to use.

© 2007-2020 Sam Allen. Send bug reports to info@dotnetperls.com.