char
array, string
A char
array can be converted into a string
. The syntax to perform this conversion can be confusing at first. The simplest approach uses the string
constructor.
For string
conversions, we can use the C# string
constructor. The StringBuilder
class
can also be used—but it is not ideal for this purpose.
Here we convert the char
array. This approach is interesting because you see the lowercase string
type has a constructor. Things like ints do not have constructors.
int
or char
, a string
is a reference type. We initialize a char
array.char
array) to letters. Recall that char
is 2 bytes. Next we use the string()
constructor.using System; // Create 3-character array. char[] array = new char[3]; array[0] = 'c'; array[1] = 'a'; array[2] = 't'; // Create string from array. string result = new string(array); Console.WriteLine($"STRING: {result}");STRING: cat
StringBuilder
Here we use the StringBuilder
type to convert a char
array to a string
. We append each char
to the StringBuilder
, and then call()
ToString
.
StringBuilder
, or add other string
data as we go along.using System; using System.Text; // Create 3-character array. char[] array = { 'c', 'a', 't' }; // Loop over the array with foreach, and append to a StringBuilder. StringBuilder builder = new StringBuilder(); foreach (char value in array) { builder.Append(value); } string result = builder.ToString(); Console.WriteLine($"STRINGBUILDER RESULT: {result}");STRINGBUILDER RESULT: cat
string
keywordThe lowercase "string
" type is an alias for the String
reference type. Strings reference external data—this is allocated on the managed heap.
The new string
constructor is overall very efficient when compared to other approaches. It is the fastest way to make a new string
in many cases.
string
, or using StringBuilder
.With a constructor, we created a new string
object from an array. You can run the example console program to prove the method works correctly.