Difference between Convert.ToString() and .ToString()

C#Type ConversionTostring

C# Problem Overview


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

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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

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

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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.

Solution 7 - C#

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

Solution 8 - C#

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

Solution 9 - C#

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

Solution 10 - C#

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)

Solution 11 - C#

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

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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.

Solution 15 - C#

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

Solution 16 - C#

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

Solution 17 - C#

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

Solution 18 - C#

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.

Solution 19 - C#

  • 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyyappan AnbalaganView Question on Stackoverflow
Solution 1 - C#RyanView Answer on Stackoverflow
Solution 2 - C#ChrisView Answer on Stackoverflow
Solution 3 - C#AlexanderView Answer on Stackoverflow
Solution 4 - C#SwatiView Answer on Stackoverflow
Solution 5 - C#João CostaView Answer on Stackoverflow
Solution 6 - C#hdoghmenView Answer on Stackoverflow
Solution 7 - C#sudeepView Answer on Stackoverflow
Solution 8 - C#AlexMelwView Answer on Stackoverflow
Solution 9 - C#Ajay SainiView Answer on Stackoverflow
Solution 10 - C#Abdul SaboorView Answer on Stackoverflow
Solution 11 - C#Gaurang DhandhukiyaView Answer on Stackoverflow
Solution 12 - C#viplovView Answer on Stackoverflow
Solution 13 - C#JohnnyView Answer on Stackoverflow
Solution 14 - C#Yogesh PatelView Answer on Stackoverflow
Solution 15 - C#Konstantin SpirinView Answer on Stackoverflow
Solution 16 - C#Senior VectorView Answer on Stackoverflow
Solution 17 - C#user632299View Answer on Stackoverflow
Solution 18 - C#Pranaya RoutView Answer on Stackoverflow
Solution 19 - C#TheGeneralView Answer on Stackoverflow