C# - Convert char[] to string

  • In C#
  • Tuesday, August 09, 2016

What is the proper way to turn a char[] into a string? The ToString() method from an array of characters doesn't do the trick.

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

Note that new string(null) yields String.Empty and not null! If you want to keep null, you can make an extension method static string ToStringSafe(this char[] buf) { return buf == null ? null : new string(buf); }.

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);

One other way:

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"