Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of ToString() in C#?

Tags:

c#

I'm using the below code in c sharp. But both the WriteLine statements are giving the same result 25. Then what is the need for converting Tostring in c sharp? Is there any special purpose?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sample
{
  class Program
  {
    static void Main(string[] args)
    {
        int value = 25;
        Console.WriteLine(value.ToString());
        Console.WriteLine(value);
        Console.ReadLine();
    }
  }
}
like image 347
abubakkar Avatar asked Jul 13 '14 05:07

abubakkar


1 Answers

If I understand your question, the purpose of ToString() is to provide a consistent mechanism to convert objects to strings. In your Console.WriteLine(value); example you are using an Overloaded version of WriteLine that takes an int, but in the general case of using an object the system needs a mechanism of providing a textual representation.

like image 185
Elliott Frisch Avatar answered Oct 19 '22 15:10

Elliott Frisch