C# Convert Char Array to String

You want to convert an array of characters into a string. It can be hard to remember how to do this. Here we review how to use the reference type string constructor. We see a simple example of how to convert these types, using the C# programming language.

Converting char arrays

First, we see the approach you can use to convert the char array. This is interesting because you see the lowercase string type has a constructor. It is a reference type, unlike int or char. Here, a char array is initialized.

=== Program that converts char array (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A. 15 character array.
        char[] c = new char[15];
        c[0] = 'O';
        c[1] = 'n';
        c[2] = 'l';
        c[3] = 'y';
        c[4] = ' ';
        c[5] = 'T';
        c[6] = 'h';
        c[7] = 'e';
        c[8] = ' ';
        c[9] = 'L';
        c[10] = 'o';
        c[11] = 'n';
        c[12] = 'e';
        c[13] = 'l';
        c[14] = 'y';

        // B. 15 character string.
        string s = new string(c);
        Console.WriteLine(s);
    }
}

=== Output of the program ===

Only The Lonely

Description of steps. The first part shows the 15 characters in the char array assigned to letters. Recall that char is two bytes in C#, and is not equivalent to byte. Next, part B shows the new string() constructor. It is the same as a regular constructor such as new Form(), but is lowercase. You can find more information on the char data type in specific.

See Char Type.

Note on string type keyword. Interestingly, the lowercase 'string' type is actually an alias for the String reference type. It's important to know that strings are reference types. This means they reference external data.

Notes on 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. The author uses it in his performance-sensitive web program. It is much faster than manually appending characters to your string, or using StringBuilder.

See New String Constructor.

MSDN reference

MSDN indicates that the String Constructor(Char[]) "Initializes a new instance of the String class to the value indicated by an array of Unicode characters." Additionally, it states that if you pass the constructor null, you get an empty string (not a null one).

Visit msdn.microsoft.com.

Summary

Here we saw how you can use the overloaded string constructor shown to instantiate a new string object from an array. You can run the example console app to prove the method works and will work in your program.

See Convert Articles.

See String Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen