176

What is the difference between Convert.ToString() and .ToString()?

I found many differences online, but what's the major difference?

animuson
  • 53,861
  • 28
  • 137
  • 147
Ayyappan Anbalagan
  • 11,022
  • 17
  • 64
  • 94
  • 7
    You say you got many differences on the web and later you ask if its for this specific reason only? What else did you find on the web? – Ryan May 14 '10 at 13:57
  • 4
    Convert.ToString() has an overload that allows to use CultureInfo, while .ToString() doesn't have such overload. – Artemix Apr 29 '14 at 10:47

19 Answers19

262

Convert.ToString() handles null, while ToString() doesn't.

Servy
  • 202,030
  • 26
  • 332
  • 449
Ryan
  • 4,443
  • 4
  • 26
  • 26
  • 4
    good.. For this specific reason only they using. two methods? – Ayyappan Anbalagan May 13 '10 at 15:48
  • Also, semi-related, see this answer for more detail: http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr/496167#496167 – JYelton May 13 '10 at 15:50
  • More information about the differences using JustDecompile/Reflector : http://www.kodefuguru.com/post/2011/06/14/Deeper-into-Convert-ToString.aspx – Jonas at Software Journey Feb 17 '12 at 17:03
  • 6
    Do you want `null` to return an empty string or throw an exception? It's kind of like the difference between casting and using `as`: silent conversion. – styfle Sep 25 '12 at 23:18
  • @Ubikuity : the link is broken – hdoghmen Aug 23 '15 at 11:05
  • Here is a copy from Internet Archive of the blog post I was mentioning: http://web.archive.org/web/20110828105257/http://www.kodefuguru.com/post/2011/06/14/Deeper-into-Convert-ToString.aspx – Jonas at Software Journey Aug 24 '15 at 09:26
  • Love it when I read a complete, direct-to-the-point, killer answer. – Matheus Felipe Oct 29 '15 at 00:26
  • To be more precise, it returns an empty string. I think this is not clear from your answer. – Dave Van den Eynde Feb 24 '20 at 10:11
  • Note, as alluded to in the question, this is just the _major_ difference between the two. As Alexander mentions, there are other subtler differences. For example, I just created a bug in some code when I thought I could use them interchangeably on an enum; but `.ToString()` gave me equivalent text and `Convert.ToString` gave me the integer value (converted to a string). – gremlin Jun 22 '23 at 19:23
70

Calling ToString() on an object presumes that the object is not null (since an object needs to exist to call an instance method on it). Convert.ToString(obj) doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null.

Chris
  • 2,959
  • 1
  • 30
  • 46
  • var arg = Request.Params.Get("__EVENTARGUMENT"); string _arg = Convert.ToString(arg); _arg is not returing String.Empty when arg is null. why? – vml19 Mar 12 '12 at 03:33
  • 2
    @Nilaa you might want to open another question asking this, instead of in comment. My first question is what *does* it return when arg is null? My first thought is that "arg" is actually of type "string" already, so you're calling the overload of Convert.ToString(...), that just returns what you pass to it. This discussion is in regards to the "object" overload of the method. – Chris Mar 12 '12 at 15:40
  • 4
    @Roshe Yeah, I just got bit by this. `Convert.ToString(string value)` returns `null` if the argument is `null`. `Convert.ToString(object value)` returns `String.Empty` if the argument is `null`. – Tim Goodman Aug 29 '13 at 15:22
26

In addition to other answers about handling null values, Convert.ToString tries to use IFormattable and IConvertible interfaces before calling base Object.ToString.

Example:

class FormattableType : IFormattable
{
    private double value = 0.42;

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (formatProvider == null)
        {
            // ... using some IOC-containers
            // ... or using CultureInfo.CurrentCulture / Thread.CurrentThread.CurrentCulture
            formatProvider = CultureInfo.InvariantCulture;
        }

        // ... doing things with format
        return value.ToString(formatProvider);
    }

    public override string ToString()
    {
        return value.ToString();
    }
}

Result:

Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString();        // 0,42
Alexander
  • 434
  • 4
  • 12
  • 1
    This should be added to the correct answer because it is quite important information. – Santhos Dec 14 '15 at 10:00
  • 2
    Just as a supplement - basing on [reference source](https://referencesource.microsoft.com/#mscorlib/system/convert.cs,1801) `IConvertible` takes precedence over `IFormattable`, which in turn takes precedence over `Object.ToString()` implementation. – Grx70 Nov 24 '18 at 09:42
11

Lets understand the difference via this example:

int i= 0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));

We can convert the integer i using i.ToString () or Convert.ToString. So what’s the difference?

The basic difference between them is the Convert function handles NULLS while i.ToString () does not; it will throw a NULL reference exception error. So as good coding practice using convert is always safe.

Swati
  • 217
  • 3
  • 3
6

You can create a class and override the toString method to do anything you want.

For example- you can create a class "MyMail" and override the toString method to send an email or do some other operation instead of writing the current object.

The Convert.toString converts the specified value to its equivalent string representation.

Sean O'Toole
  • 4,304
  • 6
  • 35
  • 43
João Costa
  • 69
  • 1
  • 1
  • 2
    Convert.ToString actually a safe method which checks for null and if value is not null it simply calls ToString method on it. So In any case, if you have overriden ToString method, Your overriden ToString method will be called. – ZafarYousafi Feb 25 '13 at 07:32
  • And this null safety only helps if you are dealing with classes. Value types can't be null and so we can safely call ToString method on them. – ZafarYousafi Feb 25 '13 at 07:36
6

The methods are "basically" the same, except handling null.

Pen pen = null; 
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException

From MSDN :
Convert.ToString Method

Converts the specified value to its equivalent string representation.

Object.ToString

Returns a string that represents the current object.

hdoghmen
  • 3,175
  • 4
  • 29
  • 33
5
object o=null;
string s;
s=o.toString();
//returns a null reference exception for string  s.

string str=convert.tostring(o);
//returns an empty string for string str and does not throw an exception.,it's 
//better to use convert.tostring() for good coding
tkanzakic
  • 5,499
  • 16
  • 34
  • 41
sudeep
  • 126
  • 1
  • 4
5

I agree with @Ryan's answer. By the way, starting with C#6.0 for this purpose you can use:

someString?.ToString() ?? string.Empty;

or

$"{someString}"; // I do not recommend this approach, although this is the most concise option.

instead of

Convert.ToString(someString);
AlexMelw
  • 2,406
  • 26
  • 35
3

For Code lovers this is the best answer.

    .............. Un Safe code ...................................
    Try
        ' In this code we will get  "Object reference not set to an instance of an object." exception
        Dim a As Object
        a = Nothing
        a.ToString()
    Catch ex As NullReferenceException
        Response.Write(ex.Message)
    End Try


    '............... it is a safe code..............................
    Dim b As Object
    b = Nothing
    Convert.ToString(b)
Abdul Saboor
  • 4,079
  • 2
  • 33
  • 25
3

Convert.ToString(strName) will handle null-able values and strName.Tostring() will not handle null value and throw an exception.

So It is better to use Convert.ToString() then .ToString();

drneel
  • 2,887
  • 5
  • 30
  • 48
3

In Convert.ToString(), the Convert handles either a NULL value or not but in .ToString() it does not handles a NULL value and a NULL reference exception error. So it is in good practice to use Convert.ToString().

robert
  • 33,242
  • 8
  • 53
  • 74
Ajay Saini
  • 39
  • 1
2

ToString() can not handle null values and convert.ToString() can handle values which are null, so when you want your system to handle null value use convert.ToString().

Kampai
  • 22,848
  • 21
  • 95
  • 95
viplov
  • 67
  • 2
2
ToString() Vs Convert.ToString()

Similarities :-

Both are used to convert a specific type to string i.e int to string, float to string or an object to string.

Difference :-

ToString() can't handle null while in case with Convert.ToString() will handle null value.

Example :

namespace Marcus
{
    class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Startup
    {
        public static void Main()
        {
            Employee e = new Employee();
            e = null;

            string s = e.ToString(); // This will throw an null exception
            s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
        }
    }
}
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
Johnny
  • 303
  • 3
  • 7
  • `Convert.ToString` do not handle `Null Exception`. it simply do: `return value == null ? string.Empty : value.ToString()` – Fabio Jan 10 '17 at 17:01
2

Here both the methods are used to convert the string but the basic difference between them is: Convert function handles NULL, while i.ToString() does not it will throw a NULL reference exception error. So as good coding practice using convert is always safe.

Let's see example:

string s;
object o = null;
s = o.ToString(); 
//returns a null reference exception for s. 

string s;
object o = null;
s = Convert.ToString(o); 
//returns an empty string for s and does not throw an exception.
Yogesh Patel
  • 818
  • 2
  • 12
  • 26
0

Convert.ToString(value) first tries casting obj to IConvertible, then IFormattable to call corresponding ToString(...) methods. If instead the parameter value was null then return string.Empty. As a last resort, return obj.ToString() if nothing else worked.

It's worth noting that Convert.ToString(value) can return null if for example value.ToString() returns null.

See .Net reference source

Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90
0

i wrote this code and compile it.

class Program
{
    static void Main(string[] args)
    {
        int a = 1;
        Console.WriteLine(a.ToString());
        Console.WriteLine(Convert.ToString(a));
    }
}

by using 'reverse engineering' (ilspy) i find out 'object.ToString()' and 'Convert.ToString(obj)' do exactly one thing. infact 'Convert.ToString(obj)' call 'object.ToString()' so 'object.ToString()' is faster.

Object.ToString Method:

class System.Object
{
    public string ToString(IFormatProvider provider)
    {
        return Number.FormatInt32(this, null, NumberFormatInfo.GetInstance(provider));
    }
}

Conver.ToString Method:

class System.Convert
{
    public static string ToString(object value)
    {
        return value.ToString(CultureInfo.CurrentCulture);
    }
}
0

Convert.Tostring() function handles the NULL whereas the .ToString() method does not. visit here.

user632299
  • 299
  • 3
  • 9
  • 22
0

In C# if you declare a string variable and if you don’t assign any value to that variable, then by default that variable takes a null value. In such a case, if you use the ToString() method then your program will throw the null reference exception. On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.

Pranaya Rout
  • 301
  • 3
  • 6
0
  • Convert.Tostring() basically just calls the following value == null ? String.Empty: value.ToString()

  • (string)variable will only cast when there is an implicit or explicit operator on what you are casting

  • ToString() can be overriden by the type (it has control over what it does), if not it results in the name of the type

Obviously if an object is null, you can't access the instance member ToString(), it will cause an exception

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141