Ayyappan Anbalagan
Ayyappan Anbalagan

Reputation: 11292

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?

Upvotes: 179

Views: 153151

Answers (19)

Yogesh Patel
Yogesh Patel

Reputation: 838

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.

Upvotes: 2

TheGeneral
TheGeneral

Reputation: 81493

  • 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

Upvotes: 0

Pranaya Rout
Pranaya Rout

Reputation: 331

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.

Upvotes: 0

user632299
user632299

Reputation: 309

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

Upvotes: 0

Senior Vector
Senior Vector

Reputation: 29

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

Upvotes: 0

Konstantin Spirin
Konstantin Spirin

Reputation: 21271

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

Upvotes: 0

Ryan
Ryan

Reputation: 4473

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

Upvotes: 265

AlexMelw
AlexMelw

Reputation: 2624

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

Upvotes: 5

Johnny
Johnny

Reputation: 303

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

Upvotes: 2

Gaurang Dhandhukiya
Gaurang Dhandhukiya

Reputation: 427

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

Upvotes: 3

hdoghmen
hdoghmen

Reputation: 3422

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.

Upvotes: 6

viplov
viplov

Reputation: 67

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

Upvotes: 2

Alexander
Alexander

Reputation: 431

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

Upvotes: 26

sudeep
sudeep

Reputation: 126

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

Upvotes: 5

Abdul Saboor
Abdul Saboor

Reputation: 4127

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)

Upvotes: 3

João Costa
João Costa

Reputation: 67

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.

Upvotes: 6

Ajay Saini
Ajay Saini

Reputation: 39

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

Upvotes: 3

Swati
Swati

Reputation: 227

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.

Upvotes: 12

Chris
Chris

Reputation: 2991

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.

Upvotes: 70

Related Questions