Home
VB.NET
String Constructor
This page was last reviewed on Mar 25, 2022.
Dot Net Perls
String has a constructor. It can be used in VB.NET programs. This allows you to convert a Char array or single char into a String instance.
Char
With the New String syntax, you can create String instances much faster than with the equivalent loop constructs. We can use the String constructor after calling ToCharArray.
String ToCharArray
Char Array
Example. First, this program is divided into 3 important routines. In the A subroutine, we show how to create a New String from an entire character array.
And In the B subroutine, we show how to create a String by repeating the letter "a" ten times.
Finally In the third subroutine C, we construct a String instance from a range of a Char array.
Result The program's execution shows that all the New String constructors worked as expected.
Module Module1 Sub Main() A() B() C() End Sub Sub A() ' Construct string from character array. Dim array(2) As Char array(0) = "a"c array(1) = "b"c array(2) = "c"c Dim example As String = New String(array) Console.WriteLine(example) Console.WriteLine(example = "abc") Console.WriteLine() End Sub Sub B() ' Construct string from repeated character. Dim example As String = New String("a"c, 10) Console.WriteLine(example) Console.WriteLine(example = "aaaaaaaaaa") Console.WriteLine() End Sub Sub C() ' Construct string from part of character array. Dim array(5) As Char array(0) = "a"c array(1) = "B"c array(2) = "c"c array(3) = "D"c array(4) = "e"c array(5) = "F"c Dim example As String = New String(array, 0, 3) Console.WriteLine(example) Console.WriteLine(example = "aBc") End Sub End Module
abc True aaaaaaaaaa True aBc True
Discussion. The string constructor is different in the C# language and the VB.NET language. VB.NET does not allow you to use the unsafe (pointer-based) methods. The C# language allows you to.
Note This means that VB.NET only has 3 overloads on the constructor, while the C# language presents 8.
A summary. The String constructor provides an essential way to create certain kinds of strings. If you need a string that is based on a range of Char array, the String constructor is ideal.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 25, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.