Difference between Convert.ToString() and .ToString()
Solution 1:
Convert.ToString()
handles null
, while ToString()
doesn't.
Solution 2:
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:
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:
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:
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.