Skip to content

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

Ganesamoorthi M

Asked Jun 21, 2018, 3:06 AM EDT1 answer
Share
LinkedInX
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
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication1  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             string str = "ganesh";  
  13.             Console.WriteLine(new string(str.Reverse().ToArray()));  
  14.             Console.WriteLine(Convert.ToString(str.Reverse().ToArray()));  
  15.             Console.WriteLine((str.Reverse().ToArray()).ToString());  
  16.             Console.ReadKey();  
  17.         }  
  18.     }  
  19. }  
  OUTPUT
  1. hsenag  
  2. System.Char[]  
  3. System.Char[]  

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • +1
    here is the changes between them :
     
    1. Convert.ToString() --> Handles null values.
     
    2.ToString() --> -It's Not.
    - type issue then throw NULL reference exception.
     
    3. new String() --> Basically it's a Constructor overload with multiple methods.
     
    Here is the code for better understanding :
     
    C#
    protected void Button1_Click(object sender, EventArgs e)
    {
    string str = "ganesh";
    string temp = new string(str.Reverse().ToArray()); // you are using overloaded method .So, need to use like this.
    Console.WriteLine(String.Format(new string(str.Reverse().ToArray()))); //Possiblly this will help you for printing your result.
    //Console.WriteLine --> there is 19 overloaded methods of "Console.WriteLine" please look into that might be help you next time.
    //Console.WriteLine(new string(str.Reverse().ToArray()));
    //Console.WriteLine(Convert.ToString(str.Reverse().ToArray()));
    //Console.WriteLine((str.Reverse().ToArray()).ToString());
    Console.ReadKey();
    }
    +1