+ 2

Convert.ToString() vs ToString() vs new string()

I am doing string reverse while I have some problem with that. I have added code and O/P below. Please give me the detail explanation for this solution. I am beginner in C#. CODE using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string str = "ganesh"; Console.WriteLine(new string(str.Reverse().ToArray())); Console.WriteLine(Convert.ToString(str.Reverse().ToArray())); Console.WriteLine((str.Reverse().ToArray()).ToString()); Console.ReadKey(); } } } OUTPUT hsenag System.Char[] System.Char[]

21st Jun 2018, 1:46 PM
Ganesamoorthi M
Ganesamoorthi M - avatar
1 Réponse
0
hi Ganesamoorthi , you don't need to use new string when you want to print a string. you can directly use this to print your string reversed : Console.WriteLine(str.Reverse()); because str.Reverse() returns string and Console.WriteLine() prints it easily. and you don't need to use ToArray() ! ToArray() returns an array ! in first Console.WriteLine you created a new string and initialized it with array of a reversed string. Its work true because new string() gets array or string. Then first Console.WriteLine prints hsenag. in second Console.WriteLine you converted your reversed string to an Array using ToArray(). Console.WriteLine() cant print array in this way. You must use a for loop and print array members one by one. I can mention that Convert.ToString() only converts other types such as numbers to string , not array ! So when you want to print an array using Console.WriteLine , it prints name of array instead members of array (System.Char[]) ! an array of chars ! So in last Console.WriteLine() you converted name of array to string and printed it again ! It looks like you converted a string to a string and printed it ! Remember that Console.WriteLine() only prints string type ! I hope my explanations is explicit :) take a look on my linkedIn account : https://www.linkedin.com/in/amir-goodarzi-a42b03148/
20th Jul 2018, 8:20 AM
Amir Goodarzi
Amir Goodarzi - avatar