Convert string to char array in C#

The ToCharArray method of the string class converts a string to a character array. The following code snippet creates a string into a char array.

  1. string sentence = "Mahesh Chand";  
  2. char[] charArr = sentence.ToCharArray();  
  3. foreach (char ch in charArr)  
  4. {  
  5.     Console.WriteLine(ch);  
  6. }   
The ToCharArray method has the following two overloaded forms:
  1. String.ToCharArray() - Copies characters of the string to a unicode character array.
  2. String.ToCharArray(Int32, Int32)  - Copies characters of the substring to a unicode character array.
Here is a complete sample code:
  1. public void StringToCharArray()  
  2. {  
  3.   
  4.     // Convert string to char array  
  5.     string sentence = "Mahesh Chand";  
  6.     char[] charArr = sentence.ToCharArray();  
  7.     foreach (char ch in charArr)  
  8.     {  
  9.   
  10.         Console.WriteLine(ch);  
  11.     }   
  12.   
  13.     // Convert char array to string  
  14.     char[] chars = new char[10];  
  15.     chars[0] = 'M';  
  16.     chars[1] = 'a';  
  17.     chars[2] = 'h';  
  18.     chars[3] = 'e';  
  19.     chars[4] = 's';  
  20.     chars[5] = 'h';  
  21.     string charsStr = new string(chars);  
  22.     string charsStr2 = new string(new char[]  
  23.     {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'});  
  24.     Console.WriteLine("Chars to string: {0}", charsStr);  
  25.     Console.WriteLine("Chars to string: {0}", charsStr2);  
  26. }   
The output looks like the following:
 
Str2BtArr.png