C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: Unlike int or char, a string is a reference type. We initialize a char array.
Char ArrayExample: We assign the 3 chars (in the char array) to letters. Recall that char is 2 bytes. Next we use the string() constructor.
CharConstructor: This constructor is the same as a regular constructor such as new Form(), but we can use a lowercase first letter.
C# program that converts char array
using System;
class Program
{
static void Main()
{
// 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}");
}
}
Output
STRING: cat
Info: We can transform the chars before we append them to the StringBuilder, or add other string data as we go along.
C# program that uses StringBuilder to convert to string
using System;
using System.Text;
class Program
{
static void Main()
{
// 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}");
}
}
Output
STRINGBUILDER RESULT: cat
Tip: It is much faster than manually appending characters to your string, or using StringBuilder.
And: If you pass the constructor null, you get an empty string (not a null one).