Convert 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.
First example. 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.
And Unlike int or char, a string is a reference type. We initialize a char array.
Info This constructor is the same as other constructors in C#, but we can use a lowercase first letter.
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.
Info We can transform the chars before we append them to the 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
Notes, string keyword. The lowercase "string" type is an alias for the String reference type. Strings reference external data—this is allocated on the managed heap.
Performance. 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.
Tip It is much faster than manually appending characters to your string, or using StringBuilder.
Summary. 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.
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 Oct 25, 2023 (edit).