Dot Net Perls

Convert Char Array to String - C#

by Sam Allen

Problem

You want to convert an array of characters into a string. It can be hard to remember how to do this. Review how to use the reference type string's constructor.

Solution: C# string constructor

This is interesting because you see the lowercase string keyword has a constructor. It is a reference type, unlike int or char. First we see a char array initialized.

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);
    }
}

Part A shows the 15 characters in the char array assigned to letters. Recall that char is 2 bytes in C#, and is not equivalent to byte.

Part B shows the new string() constructor. It is the same as a regular constructor such as new Form(), but is lowercase.

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.

Question: is the new string constructor efficient?

Yes, it is the fastest way to make a new string I have found. I use it in my performance-sensitive web program. It is much faster than manually appending characters to your string, or using StringBuilder. [Char Array Performance - dotnetperls.com]

Question: what does Microsoft say?

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). [String Constructor(Char[]) - MSDN]

Summary: converting char arrays to strings

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.

This method doesn't convert an array of strings to a single string, which you will want to use string.Join for.

Dot Net Perls
About
Sitemap
Conversion
Convert Char Array to String
Convert List to Array
Convert Bytes to Megabytes
Convert Dictionary to String
Convert Degrees Celsius to Fahrenheit
New
GZIP Accept-Encoding Request
Convert bool to int
© 2008 Sam Allen. All rights reserved.