.NET / C# - Convert char[] to string

C#.NetArraysStringChar

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

There's a constructor for this:

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

Solution 2 - C#

Use the constructor of string which accepts a char[]

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

Solution 3 - C#

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

Solution 4 - C#

One other way:

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"

Solution 5 - C#

String mystring = new String(mychararray);

Solution 6 - C#

Use the string constructor which accepts chararray as argument, start position and length of array. Syntax is given below:

string charToString = new string(CharArray, 0, CharArray.Count());

Solution 7 - C#

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBuddyJoeView Question on Stackoverflow
Solution 1 - C#Joel CoehoornView Answer on Stackoverflow
Solution 2 - C#JaredParView Answer on Stackoverflow
Solution 3 - C#Austin SalonenView Answer on Stackoverflow
Solution 4 - C#Simon AchmüllerView Answer on Stackoverflow
Solution 5 - C#Shaun RowlandView Answer on Stackoverflow
Solution 6 - C#Dilip NannawareView Answer on Stackoverflow
Solution 7 - C#Michael JView Answer on Stackoverflow