[c#] Difference between Convert.ToString() and .ToString()

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

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

This question is related to c# type-conversion tostring

The answer is


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.


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.


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.


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.


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

  • 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


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)

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();


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.
        }
    }
}

For nullable types ToString() actually handles null values:

int? i = null;
        
var s1 = i.ToString();  // returns ""

var s2 = Convert.ToString(i);   // returns ""

Just to remedy the existing answers.

Source:

https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=net-5.0


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().


To understand both the methods let's take an example:

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

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 another 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.

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().


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

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.


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


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);
    }
}

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);

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


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to tostring

How do I print my Java object without getting "SomeType@2f92e0f4"? What is the meaning of ToString("X2")? Printing out a linked list using toString ToString() function in Go to_string is not a member of std, says g++ (mingw) Confused about __str__ on list in Python How to convert an int array to String with toString method in Java Override valueof() and toString() in Java enum Checking session if empty or not Converting an object to a string